Sometimes, we want to remove insignificant trailing zeroes from a JavaScript number.
In this article, we’ll look at ways to remove insignificant trailing zeroes from a JavaScript number.
Using the Number.prototype.toString Method
We can convert a number to a number string with the JavaScript number’s toString
method.
The toString
method will remove any insignificant trailing zeroes from the number.
For instance, if we have:
const n = 1.245000
const noZeroes = n.toString()
console.log(noZeroes)
Then noZeroes
is '1.245'
.
Using the Number.prototype.toFixed Method
We can use the JavaScript number to toFixed
method to convert a number into the number string with the number of decimal places we want to show.
Then we can convert it back to a number with the parseFloat
or Number
functions.
For instance, we can write:
const n = 1.245000
const noZeroes = parseFloat(n.toFixed(5));
console.log(noZeroes)
We call toFixed
with 5 to return a number with 5 decimal places.
The toFixed
method automatically discards the insignificant trailing zeroes.
After that, we use parseFloat
to convert the number string back to a number.
Therefore, we get the same result as the previous example.
We can replace parseFloat
with Number
by writing:
const n = 1.245000
const noZeroes = Number(n.toFixed(4));
console.log(noZeroes)
and get the same result.
Conclusion
To remove insignificant trailing zeroes from a number, we can call toFixed
or toString
to convert it to a number string.
And to convert the number string back to a number, we can use the parseFloat
or Number
functions.