admin管理员组文章数量:1323524
I write line of business applications. I'd like to build a front-end end using Javascript and am trying to figure out how to deal with, for a business user, are floating point errors (I understand from a puter science perspective they might not be considered errors). I've read plenty on this and seen all kinds of rounding hacks that work on examples given but seem prone to break down unexpectedly. Is there a definitive way to do decimal math in javascript?
I write line of business applications. I'd like to build a front-end end using Javascript and am trying to figure out how to deal with, for a business user, are floating point errors (I understand from a puter science perspective they might not be considered errors). I've read plenty on this and seen all kinds of rounding hacks that work on examples given but seem prone to break down unexpectedly. Is there a definitive way to do decimal math in javascript?
Share Improve this question edited Aug 8, 2009 at 0:39 Rex Miller 2,7461 gold badge19 silver badges26 bronze badges asked May 6, 2009 at 20:53 Barry GlennBarry Glenn 1- As of June 2017, there are seven different definitive solutions – Drenai Commented Jun 9, 2017 at 14:04
3 Answers
Reset to default 6According to Douglas Crockford, the only way around this problem is scale your values to integer. Make sure it really is an integer by using Math.round
on the scaled value. (DC does not talk about the rounding part, but I discovered it was necessary. e.g. Math.round(1.1 *100))
Do calculation(s). When you are done with the math scale back to original precision. See JavaScript: The Good Parts "Floating Point" section.
One answer is to do the math in decimal instead of binary. Then you never have to worry about the decimal <=> binary conversion errors. You'd represent the numbers as binary digits in an array or a string and write the math routines yourself.
Here are some bignumber libraries you can look into if you don't want to go to that trouble:
http://jsfromhell./classes/bignumber
http://stz-ida.de/html/oss/js_bigdecimal.html.en
the only definite solution seems to be writing your own arbitrary precision number type working on strings internally -- which will be plicated and horribly slow.
本文标签: Is there a definitive solution to javascript floatingpoint errorsStack Overflow
版权声明:本文标题:Is there a definitive solution to javascript floating-point errors? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742133317a2422259.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论