1

Objective is to read data from json file using node js. Observed that numbers with more than 16 digit precision are rounded. Code:

var raw = fs.readFileSync(file);
JSON.parse(raw);

Result:

0.59190000000000009 is rounded to 0.5919000000000001

4647.3424257097241 to 4647.342425709725

6441579.5333300168 to 6441579.533330017
newuser
  • 307
  • 3
  • 24
  • This is not JSON.parse, but the float number type. – evolutionxbox Jan 28 '20 at 18:29
  • Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – evolutionxbox Jan 28 '20 at 18:30
  • You'll get the same result if you just type `var foo = 0.59190000000000009;` it has nothing to do with JSON. It's just the limit of JS numeric precision. – Barmar Jan 28 '20 at 18:30
  • Json parse is abiding by the rules of floating point numbers, which is built into the js engine. You can perhaps think about using a json library that parses big int. https://github.com/sidorares/json-bigint. But this doesnt handle decimals. So, perhaps you could also try structuring your json with the numbers as strings, then parsing the strings as BigDecimal via a library like https://www.npmjs.com/package/bignumber.js – Ja Superior Jan 28 '20 at 18:38
  • Voting to re-open. The proposed duplicate doesn't answer the question of "how to avoid" this, it only answers why this happens. – Maximillian Laumeister Jan 28 '20 at 20:31

0 Answers0