Formatting a number with exactly 2 decimal places is something that we’ve to do sometimes with JavaScript.
In this article, we’ll look at how to format a number with exactly 2 decimal places with JavaScript.
Number.prototype.toFixed
The JavaScript number’s toFixed
method lets us return a string version of the number rounded to 2 decimal places.
For instance, we can write:
console.log((10.888).toFixed(2))
Then we get:
'10.89'
from the console log.
Intl.NumberFormat Constructor
The Intl.NumberFormat
constructor also lets us round a number to 2 decimal places.
For instance, we can write:
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(formatter.format(10.888))
We use the Intl.NumberFormat
constructor with a few arguments.
The first argument is the locale we want to use the format the number.
The 2nd argument is an object with the minimumFractionDigits
and maximumFractionDigits
properties to set the min and max number of decimal places the formatted number would have.
It returns an object with the format
method with the number we want to format.
Then the console log should log '10.89'
as we expect.
Conclusion
We can use the toFixed
method or the Intl.NumberFormat
constructor to format decimal numbers to 2 decimal places with JavaScript.