Skip to content Skip to sidebar Skip to footer

Can Json.stringify Output A Whole Number Formatted As A Double?

This is an example of what I'm doing: var serialized = JSON.stringify({x: 1.0}); And this is the result I want: {'x': 1.0} But this is the result I'm getting: {'x': 1}

Solution 1:

Taking the idea of a using the replacer function of JSON.stringify and String#replace and a small addition to the number for finding the integer to replace.

It could look like this:

var s = JSON.stringify({ x: 1.0 }, function (k, v) {
        if (Number.isInteger(v)) {
            return v + 1e-10;
        }
        return v;
    }).replace(/\.0000000001/, '.0');

console.log(s);

Solution 2:

1.0 and 1 are equivalent in javascript, since there's no such thing as int/double/long in the language. Instead, you will need to add type data to make it completely clear what type you're expecting the result to be.

{"x":{"type":"double","value":1}}

Post a Comment for "Can Json.stringify Output A Whole Number Formatted As A Double?"