-1

I have a record

           [
              "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
              1000000000000000000000
           ],

JSON.stringify() converts it to the form

           [
                "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
                1e+21
           ],

JSON.stringify() writes it accordingly the same way, can this be somehow solved?

STALER
  • 186
  • 2
  • 14

2 Answers2

3

JSON.parse doesn't convert it to 1e+21, it converts it to a number that, when converted to string in the usual way, is output as the string "1e+21". But the number is the same number whether you write it as 1000000000000000000000 or 1e+21.

JSON.stringify may output it in either form; both are valid JSON numbers, and both define exactly the same number.


I should note that you need to beware of numbers of that magnitude in JavaScript (or any other language that uses IEEE-754 double-precision floating point numbers [or single-precision ones, actually]). That number is well into the range where even integers may be imprecisely represented. Any number greater than 9,007,199,254,740,992 (Number.MAX_SAFE_INTEGER + 1) may or may not have a precise representation. It happens that 10,000,00,000,000,000,000,000 (your number) does, but for instance, 9,007,199,254,740,993 doesn't, nor do any odd numbers from that point upward. At some point, you get to where only multiples of 4 can be represented; and then later it's only multiple of 8, etc. See this question's answers for more.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Okay, what should I do so that the output is not in exponential form? – STALER Sep 17 '20 at 09:30
  • See [this question](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript)'s answers. I've also added a note to the answer about the magnitude of the number you're using, which is problematic. – T.J. Crowder Sep 17 '20 at 09:36
0

If you still need to get 1e+21 as 1000000000000000000000, you can use (1e+21).toLocaleString().split(',').join('')

but actually, you don't need to convert it if you want to use it as a number, because they are absolutely the same.

Instead, you can keep the number as string and use +'1000000000000000000000' or parseInt('1000000000000000000000') when you need to use it as a number.

  • `(1e+21).toLocaleString().split(',').join('')` actually converts number `1e+21` to a string `'1000000000000000000000'` –  Sep 17 '20 at 09:42
  • **That may or may not work, depending on locale.** Details [in the specification](https://tc39.es/ecma262/#sec-number.prototype.tolocalestring). See also [this question](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript)'s answers. `(1e+21).toLocaleString().replace(/\D/g, "")` would be more reliable if you knew the number was an integer as this one is, but I wouldn't use it in production. – T.J. Crowder Sep 17 '20 at 09:43