【发布时间】:2013-03-01 06:33:45
【问题描述】:
警报(5.30/0.1);
这给出了52.99999999999999,但应该是53。任何人都可以告诉如何以及为什么?
我想找到一个数字可以被一个给定的数字整除。请注意,其中一个数字可能是浮点数。
【问题讨论】:
标签: javascript
警报(5.30/0.1);
这给出了52.99999999999999,但应该是53。任何人都可以告诉如何以及为什么?
我想找到一个数字可以被一个给定的数字整除。请注意,其中一个数字可能是浮点数。
【问题讨论】:
标签: javascript
要查找数字 x 是否可以被数字 y 整除,您必须执行 x % y(取模)。如果结果为 0,则它是完全可整除的,任何其他都不是。
【讨论】:
0 不同的值。
您可以通过以下方式获得它: 变量数 = (5.30/0.1); alert(num.toFixed(2));
这会给你 53.00。
【讨论】:
出于同样的原因
0.1 * 0.2 //0.020000000000000004
某些十进制数无法在 IEEE 754 中表示,这是 JavaScript 使用的数学表示。如果您想在问题中对这些数字进行算术运算,最好先将它们相乘,直到它们成为整数,然后再除以它们。
【讨论】:
将数字缩放为整数。然后对结果取模。
alert((5.30*10) % (0.1*10));
【讨论】:
(1.5876 * 100000) % (0.0001 * 100000) 可以
现在您已经阅读了我评论的文章,您应该知道问题的根源。 您可以通过缩放浮动来部分解决这个问题...
然后写一个函数:
function isDivisable(n, d) {
var ndI = 1 + "".indexOf.call(n, "."); //Index of the Number's Dot
var ddI = 1 + "".indexOf.call(d, "."); // Index of the Divisors Dot
if (ndI || ddI) { // IF its a float
var l = Math.max(("" + n).length - ndI, ("" + d).length - ddI); //Longest Decimal Part
var tmpN = (n * Math.pow(10, l)); //scale the float
var tmpD = (d * Math.pow(10, l));
return !~((tmpN % tmpD) - 1); //Substract one of the modulo result, apply a bitwise NOT and cast a boolean.
}
return !~((n % d) - 1); // If it isnt a decimal, return the result
}
console.log(isDivisable(5.30, 0.1));//true
这是JSBin
不过……
由于整数以 64 位精度存储,因此最大精度约为 (2^53), 当缩放更大的数字时,您很快就会超过最大精度。
因此,为 javascript 获取某种 BigInteger 库可能是个好主意 如果你想测试浮点数的可分性
【讨论】: