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?