Subtracting long numbers in javascript

后端 未结 6 1816
执笔经年
执笔经年 2020-12-02 01:44

Why is q == 0 in the following script?



        
6条回答
  •  Happy的楠姐
    2020-12-02 02:19

    Because numbers in JavaScript are floating-point. They have limited precision.

    When JavaScript sees a very long number, it rounds it to the nearest number it can represent as a 64-bit float. In your script, start and end get rounded to the same value.

    alert(1234567890123456789);   // says: 1234567890123456800
    alert(1234567890123456799);   // says: 1234567890123456800
    

    There's no built-in way to do precise arithmetic on large integers, but you can use a BigInteger library such as this one.

提交回复
热议问题