Skip to content

Number with too many decimal places ends up in scientific notation

I am getting a price from a 3rd party API which is returned in scientific notation. When I actually check this price on their site, its shown as 1.20 but the api returns 1.2052626e

I want to perform a multiplication with that price field and format it to a currency string but it always returns as 0.00 cause of that scientific notation. Is there any way I can turn this 1.2052626e into a 1.20 or to a fixed amount of decimals for all scientific notations returned by that api?

Answer

You can use parseFloat to convert it to a decimal number and then use the toFixed method on it.

const res = "1.2052626e";
console.log(parseFloat("1.2052626e").toFixed(2)); // as string

console.log(+parseFloat("1.2052626e").toFixed(2)); // as number