6

Tell me please, how do I get the number out of the json, why do zeros appear at the end of the number?

var a = '{ "n": 870744036720833075 }';
var json = JSON.parse(a);

document.getElementById('test').innerHTML = json.n; // 870744036720833000 why?

How can I fix this?

Grhm
  • 6,726
  • 4
  • 40
  • 64
  • You might need to express this number as either a string or a condensed notation, because it exceeds the `Number.MAX_SAFE_INTEGER` constant (9007199254740991) – Sterling Archer Nov 08 '17 at 19:55
  • check this https://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript – Sanchit Patiyal Nov 08 '17 at 19:57

1 Answers1

6

This integer exceeds what Javascript considers a safe integer. You can test this by running Number.isSafeInteger(870744036720833075), which will return false. Because of this, the number is stored to the maximum available precision.

See here for an explanation of max safe integers. A sideeffect of this can be noticed in the documentation.

Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

This means that from Javascript's point of view, the number you are creating, and the number it gives you would compare to the same thing.

UPDATE

To store the number, you will have to treat it as a string. Change your json to be var a = '{ "n": "870744036720833075" }';

If you need to perform mathematical operations on them, you can find some Javascript libraries that perform mathematical operations on string encoded numbers, such as strint, or the ones suggested in comments.

UPDATE

If you are getting this from an external api, you will have to parse the JSON yourself. This answer might be a good start for you.

Kolichikov
  • 2,944
  • 31
  • 46