50

In JavaScript, I have a number which is 21 digits, and I want to parse it.

Does a parseDouble method exist in JavaScript?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Priyesh Shah
  • 609
  • 2
  • 6
  • 8

1 Answers1

85

It's not possible to natively deal with a 21-digit precision number in JavaScript.

JavaScript only has one kind of number: "number", which is a IEEE-754 Double Precision ("double") value. As such, parseFloat in JavaScript is the equivalent of a "parse double" in other languages.

However, a number/"double" only provides 16 significant digits (decimal) of precision and so reading in a number with 21-digits will lose the 5 least significant digits1.

For more precision (or accuracy) a "big number" library must be used;

1 Information can be lost when encoding as an IEEE "double", which cannot encode all decimal values exactly, but that's another question..

Pankaj
  • 401
  • 1
  • 6
  • 16
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • I have to parse a 21 digit number which does not have any decimal places. BigInteger and BigNumber can only parse upto 16 digits with precision. But I have a number larger than that and I need that to be parsed precisely. Pls advise. Suggestions with syntax highly appreciated. Thank you. – Priyesh Shah Jan 22 '14 at 10:22
  • 1
    @PriyeshShah You need to start with a *string* and pass this to BigInteger/BigNumber to parse. As soon as you have a *number* value in JavaScript then it's subject to the limits above - that is, it has *already* lost the less significant digits. – user2864740 Jan 22 '14 at 18:16