how to reduce numbers' significance in JSON's stringify

dr jerry picture dr jerry · Feb 18, 2012 · Viewed 7.4k times · Source

I have an array with numbers (coordinates) and I want to display those using JSON like so

 JSON.stringify(array);

My array looks like:

[{"x":-0.825,"y":0},
 {"x":-1.5812500000000003,"y":-0.5625},
 {"x":-2.2515625000000004,"y":-1.546875}]

But I'm only interested in the first (lets say) 4 significant digits, i.e.

[{"x":-0.825,"y":0},
 {"x":-1.5813,"y":-0.5625},
 {"x":-2.2516,"y":-1.5469}]

Is there a way to easily ditch the remaining insignificant numbers?

Answer

georg picture georg · Feb 18, 2012

Native JSON.stringify accepts the parameter replacer, which can be a function converting values to whatever is needed:

a = [0.123456789123456789]
JSON.stringify(a, function(key, val) {
    return val.toFixed ? Number(val.toFixed(3)) : val;
})

>> "[0.123]"