How to use large integers from a REST API in Javascript

ismail.lagouilly_1386495
Blog Categories: 

If you have ever noticed that large integers loose precision in Javascript, then this article will help you.

For example, if we use a Rest API to send an ID (19 digits for example) into one of our pages, this ID will be parsed and therefore unusable.

Here's an example of a value returned by the API compared to what Javascript displays :
Java/Groovy : "7300304369714702521"
Javascript : "7300304369714702000"

This comes from the fact that in Java "64 bits" integers are used compared to "53 bits" in Javascript.

Here are some articles that explain this subject more in detail:
https://2ality.com/2012/07/large-integers.html
https://stackoverflow.com/questions/17320706/javascript-long-integer

For this reason, it's recommended to return IDs in their String format in order to be sure that the content will be preserved.

Twitter's API's for example provide IDs in both number and string format (id and id_str) to avoid this known behavior.

I hope this article helps.

Notifications