乘以100时出现神秘计算错误 [英] Mysterious calculation error when multiply by 100
问题描述
以下脚本包含一个非常奇怪的错误。我想检查一个值是否为正整数。为此,我乘以100将值括起来。如果我测试0.07,则脚本不计算值7,而是计算值7.00000001。我可以对值进行舍入,但我想知道为什么以这种方式计算值。
The following script contains a very strange error. I want to check if a value is a positive integer. To do this, I multiply by 100 to enclose the value to decimal. If I test 0.07, the script does not calculated the value 7, but the value 7.00000001. I could round the value, but I would like to know why the value is calculated this way.
<script type="text/javascript">
var isPositiveInt = function(i) {
i = i*100;
return ((i % 1) == 0 && i >= 0);
};
</script>
<a href="#" onclick="alert(isPositiveInt('0.07')); return false;">Try it out!</a>
0.05,0.06和0.08正常工作。但是0.07会发生什么?如果有人能向我解释,我会很高兴。
0.05, 0.06 and 0.08 works fine. But what happens with 0.07? I would be happy if someone could explain that to me.
推荐答案
这是因为javascript会在内部将所有内容都转换为double。因此,由于浮点不准确,所有计算都会产生一些噪音:浮点不准确示例
That's because javascript casts everything to a double internally. As a result, all calculations pick up some noise due to floating point inaccuracy: Floating point inaccuracy examples
解决此问题的一种方法是在所有中间计算后向下舍入到最近的int。
One way to fix this issue, is to just round down to the nearest int after all intermediate calculations.
这篇关于乘以100时出现神秘计算错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!