How to Format a Number with Two Decimals in JavaScript

There are several methods used to format a number with two decimals in JavaScript. Let’s see the difference between the methods.

Intl.NumberFormat

You can use the Intl.NumberFormat constructor. It is supported in major browsers and in Node.js:

Javascript Intl.NumberFormat constructor
const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formatter.format(3.005)); // "3.01" console.log(formatter.format(2.345)); // "2.35"

toLocaleString

The alternative of the above method is the toLocaleString method which internally uses the Intl API:

Javascript toLocaleString method
const format = (num, decimals) => num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(format(3.005)); // "3.01" console.log(format(2.345)); // "2.35"

toFixed

One of the methods used is the toFixed method which returns a string:

Javascript toFixed method
let num1 = 6.8; let num2 = 264.1364; console.log("num1.toFixed() is : " + num1.toFixed(2)); console.log("num2.toFixed() is : " + num2.toFixed(2));
The toFixed() method sometimes returns rounded value, sometimes not.

For example:

Javascript toFixed method
let num1 = 3.005; console.log("num1.toFixed() is : " + num1.toFixed(2)); // "3.00"

To round the number, you should use the math.round() function which returns the value of a number rounded to the nearest integer:

Javascript toFixed method
let num1 = 3.005; console.log("num1.toFixed() is : " + (Math.round(num1 * 100) / 100).toFixed(2)); // "3.01"

Numbers

The Number object is a wrapper object that allows working with numerical values. There are two types of numbers in modern JavaScript: Regular and BigInt. The math is a built-in object that has properties and methods for mathematical constants and functions. The math object works with the Number type not with BigInt.