如何在 JavaScript 中使用 parseInt()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11338703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use parseInt() in JavaScript
提问by dolaameng
I was using parseInt() to get some big prime numbers, but it's working as expected. For example,
我正在使用 parseInt() 来获取一些大素数,但它按预期工作。例如,
parseInt("18014398241046527", 10); // Gives me 18014398241046528??
parseInt("18014398241046528", 10); // Gives me 18014398241046528
parseInt("18014398241046529", 10); // Still gives me 18014398241046528??
I tested them on both Chrome version 20.0.1132.47 and Firefox 12.0. Was this because the numbers that I was trying to parse were too large?
我在 Chrome 版本 20.0.1132.47 和 Firefox 12.0 上测试了它们。这是因为我试图解析的数字太大了吗?
采纳答案by st-boost
This is not an issue with parseInt
; this number is too long (too precise - see nhahtdh's answer) for JavaScript's Number data type (proof: +"18014398241046527"
yields 18014398241046528
as well).
这不是问题parseInt
;对于 JavaScript 的 Number 数据类型,这个数字太长(太精确 - 请参阅 nhahtdh 的答案)(证明:+"18014398241046527"
yields18014398241046528
也是如此)。
I think the only way to work around this is to input the number as a string and work on it in chunks.
我认为解决此问题的唯一方法是将数字作为字符串输入并分块处理。
回答by nhahtdh
A number in JavaScript is floating point double precision, which can only contain up to 53-bit of precision (approximately 16 decimal digits). The number you have in the question is 17 digits, so it cannot store the number exactly.
JavaScript 中的数字是浮点双精度,最多只能包含 53 位精度(大约 16 位十进制数字)。您在问题中的数字是 17 位数字,因此它无法准确存储该数字。
Wikipedia article on JavaScript syntax/Number.
维基百科关于JavaScript 语法/数字的文章。
Reference to JavaScript (1.1) standard.