2013-03-13 102 views
0

alert(5.30/0.1);javascript部分给出错误的答案?

这给出52.99999999999999,但应该是53。任何人都可以说出如何和为什么?

我想找到一个数字可以被给定的数字整除。请注意,其中一个数字可能是一个浮点数。

+6

[什么每台计算机科学家应该知道关于浮点运算(HTTP:// docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – C5H8NNaO4 2013-03-13 11:02:08

回答

-1

要查找某个数字x是否可以被数字y整除,则必须使用x % y(模数)。如果结果为0,则它​​是完全可分的,其他则不是。

+3

不幸的是,在这种情况下,这将返回一个与“0”不同的值。 – insertusernamehere 2013-03-13 11:05:10

-1

您可以通过以下方式获取: var num =(5.30/0.1); alert(num.toFixed(2));

这会给你53.00。

+0

问题说“*我想找到一个数字可以被给定的数字整除*”,大概这意味着“完全可分”。如果丢弃小数点后的所有内容,则每个负面结果都会以误报形式出现。 – Quentin 2013-03-13 11:05:52

+0

@Quentin看到第一行: 这给出52.99999999999999,但应该是53.任何人都可以告诉如何以及为什么? – 2013-03-13 11:08:53

+0

- 见第二行。 “*我想找到一个数字可以被给定的数字整除。*”。您的回答只处理第一行,而不考虑上下文。背景非常重要。 – Quentin 2013-03-13 11:30:30

9

对于

0.1 * 0.2 //0.020000000000000004 

一些十进制数不能在IEEE 754,由JavaScript中使用的数学表示来表示同样的道理。如果你想在你的问题中用这些数字进行算术运算,最好将它们相乘,直到它们是整数,然后将它们分开。

7

将数字缩放成整体。然后模拟结果。

alert((5.30*10) % (0.1*10)); 
+0

这总是不起作用的情况如下: (1.5876 * 10000)%(0.0001 * 10000)结果为0.999999999998 – Trans 2017-05-25 04:08:45

+0

@Trans但是(1.5876 * 100000)%(0.0001 * 100000)' – DickieBoy 2017-05-25 08:30:26

0

现在你已经阅读了我评论的文章,​​你应该知道你的问题的根源。 您可以部分地解决,通过缩放你漂浮...

然后只写一个函数:

  • 如果它是一个浮动
    • 刻度上的数字
  • 回报数字可分性的布尔表示法

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), ,你很快就会超过最大精度的时扩大更大的数字。

所以它可能是一个好主意,得到某种BigInteger的图书馆为JavaScript 如果你想测试的float整除