警报(5.30/0.1);
这给出52.99999999999999
但应该是53
. 任何人都可以告诉如何以及为什么?
我想找到一个数字可以被给定的数字整除。请注意,其中一个数字可能是浮点数。
警报(5.30/0.1);
这给出52.99999999999999
但应该是53
. 任何人都可以告诉如何以及为什么?
我想找到一个数字可以被给定的数字整除。请注意,其中一个数字可能是浮点数。
出于同样的原因
0.1 * 0.2 //0.020000000000000004
一些十进制数不能用 IEEE 754 表示,这是 JavaScript 使用的数学表示。如果您想在问题中对这些数字进行算术运算,最好先将它们相乘,直到它们成为整数,然后再除以它们。
将数字缩放为整数。然后对结果取模。
alert((5.30*10) % (0.1*10));
现在您已经阅读了我评论的文章,您应该知道问题的根源。您可以通过缩放浮动来部分解决这个问题......
然后只需编写一个函数:
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 库可能是一个好主意
要确定一个数字x
是否可以被一个数字整除,y
你必须做x % y
(模)。如果结果为 0,则它是完全可除的,任何其他都不是。
您可以通过以下方式获得它: var num = (5.30/0.1); alert(num.toFixed(2));
这会给你 53.00。