最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use parseInt() in JavaScript - Stack Overflow

programmeradmin1浏览0评论

I was using parseInt() to get some big prime numbers, but it's working as expected. For example,

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?

I was using parseInt() to get some big prime numbers, but it's working as expected. For example,

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?

Share Improve this question edited Dec 21, 2015 at 18:44 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jul 5, 2012 at 6:14 dolaamengdolaameng 1,4372 gold badges18 silver badges25 bronze badges 3
  • 1 Not too large: too many significant digits. – nnnnnn Commented Jul 5, 2012 at 6:17
  • P.S. Not a problem with parseInt(), just the way JS numbers work. There are a few JS libraries around that can handle more significant digits, e.g., BigNumber. – nnnnnn Commented Jul 5, 2012 at 6:24
  • It seems there is a pattern for overflowing here. It all starts from 2 bytes and 01, 10, 11 will be 10 and 00 will be 00<pre><code>0 '->' 11111111111111110 1 '->' 11111111111111112 2 '->' 11111111111111112 3 '->' 11111111111111112 4 '->' 11111111111111114 5 '->' 11111111111111116 6 '->' 11111111111111116 7 '->' 11111111111111116 8 '->' 11111111111111118</code></pre> – dolaameng Commented Jul 5, 2012 at 7:19
Add a ment  | 

2 Answers 2

Reset to default 5

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.

Wikipedia article on JavaScript syntax/Number.

Reference to JavaScript (1.1) standard.

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).

I think the only way to work around this is to input the number as a string and work on it in chunks.

发布评论

评论列表(0)

  1. 暂无评论