Last active
December 19, 2015 07:09
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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