Skip to content

Instantly share code, notes, and snippets.

@arch1t3ct
Last active December 19, 2015 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arch1t3ct/5917193 to your computer and use it in GitHub Desktop.
Save arch1t3ct/5917193 to your computer and use it in GitHub Desktop.
Javascripts supports precise numbers up to 9 007 199 254 740 992. Everything beyond that looses precision. I found myself loosing this precision when I had to parse a JSON with big numbers. A solution (although hacky) is to manually convert numbers to strings before parsing. Note: this will convert numbers to strings from 1 000 000 000 000 000 a…
var json_string = '{"big_number": 3754019163539080706}';
var json_string_converted = json_string
.replace(/\s*:\s*(\d{16,})\s*\}/mg, ':"$1"}')
.replace(/\s*:\s*(\d{16,})\s*\,/mg, ':"$1",');
var json = JSON.parse(json_string);
var json_converted = JSON.parse(json_string_converted);
console.log(json); // Precision lost
console.log(json_converted); // Precision not lost
// Converting back
var stringified = JSON.stringify(json_converted);
stringified = stringified
.replace(/\s*:\s*"(\d{16,})"\s*\}/mg, ':$1}')
.replace(/\s*:\s*"(\d{16,})"\s*\,/mg, ':$1,');
console.log(stringified); // Number type restored
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment