Alex Rivera | Logout

how to reduce numbers' significance in JSON's stringify

Asked 2012-02-18T08:45:48.293
25

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?

Edit
Report

1 Answer

1

A bit of overkill, but this should work in all situations.

function prepareArrayForJSON(array) {
    var i = 0;
    while (i < array.length) {
        if (typeof array[i] === 'number') {
            array[i] = array[i].toPrecision(4);
        } else if(typeof array[i] === 'object') {
            if (array instanceof Object) {
                prepareObjectForJSON(array[i]);
            } else if (array instanceof Array) {
                prepareArrayForJSON(array[i]);
            }
        }
    }
}

function prepareObjectForJSON(obj) {
    var i;
    for (i in obj) {
        if (obj.hasOwnProperty(i)) {
            if (typeof obj[i] === 'number') {
                obj[i] = obj[i].toPrecision(4);
            } else if(typeof obj[i] === 'object') {
                if (obj instanceof Object) {
                    prepareObjectForJSON(array[i]);
                } else if (obj instanceof Array) {
                    prepareArrayForJSON(obj[i]);
                }
            }
        }
    }
}

Enjoy yourself

answered 2012-02-18T08:54:10.977

Your Answer