What is best way to parse JSON number as String in javascript
Example:
{
"a": 10.00
}
Notice I do not have control over value 10.00. I cannot add there "+''". I want to keep the decimal places, but it is not rule that there have to be 2 decimals.
Result should be 10.00 not 10
If you need exactly the same number of decimals, the only way is if the JSON present the value as string. If you have no control over the source, you could edit the JSON before parsing, adding the quotes, but that could bring several problems. This needs to be tested toroughly.
json = '{ "a": 10.00, "b":2.1020, "d":0.20,"c": "21" }';
json = json.replace(/:\s*[^"0-9.]*([0-9.]+)/g, ':"$1"');
console.log(json);
console.log(JSON.parse(json));
You can use JSON.parse with a reviver argument
const json = '{"a":{"b":0.1}}'
const data = JSON.parse(json, (_key, value, data) => typeof value === 'number' ? data.source : value)
console.log(data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With