I need to write a custom JSON.stringify function that ensures numbers that end with .0 retain their decimal values, like when passed through .toFixed(). I understand that this is not how javascript numbers work, the requirement comes from my users. If a value an integer and does not include a .0, it should remain an integer without a decimal place. If a value is a float, it should remain a float. And if a value is a float with any .0000… type empty value in the decimal place, it should remain a float with the same number of zeroes in the decimal place.
I have written the following function:
function monacoStringify(json: any, spacing: number) {
return JSON.stringify(json, (key: string, value: any) => {
if(typeof value === 'number') {
const numString = `${value}`;
const dotIdx = numString.indexOf('.');
if(dotIdx !== -1) {
const dotSplit = numString.split('.');
const numsAfterDecimal = dotSplit[1].length;
return value.toFixed(numsAfterDecimal);
}
return value;
}
return value;
}, spacing)
}
export default monacoStringify;
That I directly pass the following Ajax response:
But the value variable on line 3 is 13
, not 13.0
like it says in the developer console’s network response tab.
Is there any way to keep these values formatted exactly the way they are received?