Categories
JavaScript Answers

How to Format a Number with Exactly Two Decimal Places in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *