Last active
May 3, 2023 07:45
-
-
Save liabru/11263868 to your computer and use it in GitHub Desktop.
Limit precision of floating point numbers in a JSON string in JavaScript
This file contains hidden or 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 testObject = { | |
pi: Math.PI, | |
e: Math.E, | |
one: 1, | |
x: 1.5, | |
str: "1.2345" | |
}; | |
var places = 2, | |
json = JSON.stringify(testObject, function(key, value) { | |
// limit precision of floats | |
if (typeof value === 'number') { | |
return parseFloat(value.toFixed(places)); | |
} | |
return value; | |
}); | |
console.log(json); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment