虽然3 * 0.1不能完全表示,为什么Javascript能正确计算0.15 * 2? [英] While 3 * 0.1 cannot be represented exactly, why can Javascript properly calculate 0.15 * 2?
问题描述
可能重复:
JavaScript的浮点数学破坏?
在Javascript中,
3 * 0.1 = 0.30000000000000004
我认为这是由于语言的数字系统0.3不能准确表示。但为什么以下?
0.15 * 2 = 0.3
$ p
$ b同样,
0.1 + 0.2 = 0.30000000000000004
code>但是
0.15 + 0.15 = 0.3
情况如何?
解决方案
但是,为什么以下?
0.15 $ 2 = 0.3
结果并不完全是0.3,但它足够接近,所以当最低有效位数四舍五入以显示该值时,它将舍入到0.3。
值
0.1
和0.15
也不准确,但代表0.1
的错误似乎大于0.15
。当您在计算中使用这些值时,错误会累积起来,并且迟早会变得足够大,而不会在显示值时四舍五入。Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?In Javascript,
3 * 0.1 = 0.30000000000000004
I think this is due to the language's number system where 0.3 cannot be accurately represented. But why the following?
0.15 * 2 = 0.3
Similarly,
0.1 + 0.2 = 0.30000000000000004
But
0.15 + 0.15 = 0.3
How's so?
解决方案But why the following?
0.15 * 2 = 0.3
The result isn't exactly 0.3, but it's close enough so that when the least significant digits are rounded off to display the value, it's rounded to 0.3.
The values
0.1
and0.15
are not exact either, but the error representing0.1
seems to be larger than for0.15
. When you use the values in calculations, the errors accumulate, and sooner or later they become large enough not to be rounded off when the values are displayed.这篇关于虽然3 * 0.1不能完全表示,为什么Javascript能正确计算0.15 * 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!