Skip to content

Instantly share code, notes, and snippets.

@liabru
Last active May 3, 2023 07:45
Show Gist options
  • Save liabru/11263868 to your computer and use it in GitHub Desktop.
Save liabru/11263868 to your computer and use it in GitHub Desktop.
Limit precision of floating point numbers in a JSON string in JavaScript
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