1

I can't find how the number of decimal places is calculated in JavaScript when converting to a string.

I want to transmit numbers through JSON but JSON.stringify is generating different lengths for the decimal places.

For instance:

JSON.stringify(Math.PI).length // 17 (15 decimal places)
JSON.stringify(1/3).length // 18 (16 decimal places)
JSON.stringify(0.1 + 0.2).length // 19 (17 decimal places)

It happens the same if I convert to string (e.g. String(1/3).length) so it looks like JSON.stringify under the covers is converting to string.

I've tried this on chrome, firefox and node and the representation is consistent so it doesn't look like some console quirk.

Back to my initial question (but a bit rephrased):

How are the maximum number of decimal places in JavaScript calculated when converting a number to string?

Artur Carvalho
  • 6,901
  • 10
  • 76
  • 105
  • 2
    It's constrained by the IEEE 754 number representation. So, it's part of the 64 bits available for numbers and how those are converted from base 2 to base 10 (and the oddities around that). – VLAZ Apr 26 '21 at 15:21
  • A more productive question might be to tell us what you're trying to do. Because just the knowledge of base 2 -> base 10 floating point conversion isn't that relevant by itself. – VLAZ Apr 26 '21 at 15:23
  • @VLAZ I want to understand how the language works. I don't get how the linked questions responds to why Math.PI has 15 decimal places and 1/3 has 16. – Artur Carvalho Apr 26 '21 at 16:04
  • OK, so you want a full course in floating point math? Seems a bit broad for SO. – VLAZ Apr 26 '21 at 16:20
  • I'd like a non-condescending answer for why `String(Math.PI) !== String(Math.LN2)`. – Artur Carvalho Apr 27 '21 at 09:39

0 Answers0