Remove insignificant trailing zeros from a number?

I had a similar instance where I wanted to use .toFixed() where necessary, but I didn’t want the padding when it wasn’t. So I ended up using parseFloat in conjunction with toFixed.

toFixed without padding

parseFloat(n.toFixed(4));

Another option that does almost the same thing
This answer may help your decision

Number(n.toFixed(4));

toFixed will round/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0’s. For example:

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

Because even if you define a number with trailing zeros they’re dropped.

var n = 1.23000;
 // n == 1.23;

Leave a Comment