有没有一个确定的解决方案的JavaScript浮点错误? [英] Is there a definitive solution to javascript floating-point errors?
问题描述
Math.round
确保它确实是一个整数。 (DC不会谈论舍入部分,但是我发现这是必要的,例如 Math.round(1.1 * 100))
做计算。当你完成数学规模回到原来的精度。请参阅 JavaScript:The Good Parts Floating Point部分。 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 computer 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?
According 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.
这篇关于有没有一个确定的解决方案的JavaScript浮点错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!