在javascript中减去长数字 [英] Subtracting long numbers in javascript
问题描述
为什么以下脚本中的q == 0?
Why is q == 0 in the following script?
<script>
var start = 1234567890123456789;
var end = 1234567890123456799;
var q = end - start;
alert(q);
</script>
我认为结果应该是10.减去这两个数字的正确方法是什么?
I would think the result should be 10. What is the correct way to subtract these two numbers?
推荐答案
因为JavaScript中的数字是浮点数。它们的精度有限。
Because numbers in JavaScript are floating-point. They have limited precision.
当JavaScript看到一个很长的数字时,它会将它四舍五入到它可以表示为64位浮点数的最近数字。在您的脚本中,开始
和结束
将四舍五入为相同的值。
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
没有内置的方法可以对大整数进行精确算术,但是你可以使用BigInteger库,例如这一个。
There's no built-in way to do precise arithmetic on large integers, but you can use a BigInteger library such as this one.
这篇关于在javascript中减去长数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!