How to convert float values in JSON to two decimal place using Javascript

I have a JSON file that contains numbers of type float. I would like to convert them to two decimal places before using the file in a react application. I understand that I need to use number.toFixed(2) to achieve that. How could I achieve that in the JSON file? A sample of the file:

[
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 3457.7132034355964,
    "value_avg_minus_stdv": 3415.2867965644036,
},
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 4457.7132034355964,
    "value_avg_minus_stdv": 3425.2867965644036,
}
]

The final result should be :

[
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 3457.71,
    "value_avg_minus_stdv": 3415.29,
},
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 4457.71,
    "value_avg_minus_stdv": 3425.29,
}
]

Thanks!


You could pass reviver function to the JSON.parse method to prescribes how the value originally produced by parsing is transformed, before being returned:

JSON.parse(jsonString, (key, value) =>
  typeof value === "number" ? Math.round(value * 100) / 100 : value
);

Replace Math.round(value * 100) / 100 with Math.round((value + Number.EPSILON) * 100) / 100 or +value.toFixed(2) or other methods as you wish.

More about JSON.parse


use toFixed

Like this

[
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 3457.7132034355964,
    "value_avg_minus_stdv": 3415.2867965644036,
},
{
    "module": "prado2",
    "current_value": 3437.0,
    "value_avg": 3436.5,
    "value_avg_plus_stdv": 4457.7132034355964,
    "value_avg_minus_stdv": 3425.2867965644036,
}
].map(x => ({
    ...x,
    value_avg_plus_stdv: +x.value_avg_plus_stdv.toFixed(2),
    value_avg_minus_stdv: +x.value_avg_minus_stdv.toFixed(2)
}))

Edit - toFixed will return a string, so add a + to convert it to number