Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json max int number

Tags:

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?

like image 626
Иван Иванов Avatar asked Nov 08 '17 19:11

Иван Иванов


People also ask

Can JSON have integer values?

JSON NumbersNumbers in JSON must be an integer or a floating point.

Is there a limit to JSON parse?

The Limitations of Parse JSONPower Automate has a usage limit of 5,000 API requests.

Can JSON contain numbers?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.


1 Answers

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.

like image 76
Kolichikov Avatar answered Sep 20 '22 13:09

Kolichikov