toFixed
trims digits after the decimal point, but your actual number is very large - it doesn't have a decimal point.
If you don't know in advance whether the number is large or not, one option is to call toFixed(2)
on the number first (trimming off and properly rounding digits past the decimal point for small numbers), then using a regular expression to take the numeric part only (removing the e
if it exists), then call toFixed(2)
again (trimming off and properly rounding digits past the decimal point for large numbers):
const fix = num => Number(
num.toFixed(2).match(/\d+(?:\.\d+)?/)[0]
).toFixed(2);
console.log(fix(9.074701047887939e+304));
console.log(fix(123.4567));
console.log(fix(12345));