Oftentimes, we have to format a floating-point number into the format we want in JavaScript.
In this article, we’ll look at how to format a floating-point number into the format we want with JavaScript.
Math.round
We can use Math.round
to round a number into the number of decimal places we want by multiplying the original number 10 to the power of the number of decimal places we want to round to.
Then we pass that number into Math.round
, and we divide the rounded number by the same number we multiplied the original number with.
For instance, we can write:
const original = 123.456
const result = Math.round(original * 100) / 100;
console.log(result)
We multiply original
by 100, which is 10 to the power of 2.
So we round to 2 decimal places.
And we divide by 100.
Then result
is 123.46.
This also works if we also round to other numbers of decimal places.
For instance, we can write:
const original = 123.45678
const result = Math.round(original * 1000) / 1000;
console.log(result)
And result
is 123.457.
Number.prototype.toFixed
We can call the toFixed
method to return a string with the number rounded to the given number of decimal places.
For instance, we can write:
const original = 123.45678
const result = original.toFixed(3)
console.log(result)
Then result
is ‘123.457’
.
3 is the number of decimal places to round to.
result
is a string instead of number in the previous example.
This is the easier way to format a number to the number of decimal places we want.
Conclusion
We can format a floating-point number into the number of decimal places we want with Math.round
or the number’s toFixed
method.