[Solved] Formatting a number with exactly two decimals in JavaScript


Formatting numbers with exactly two decimals in JavaScript can be a tricky task. Fortunately, there are a few different methods that can be used to achieve this. In this article, we will discuss the various ways to format a number with exactly two decimals in JavaScript. We will also provide examples of each method so that you can see how it works in practice. By the end of this article, you should have a better understanding of how to format a number with exactly two decimals in JavaScript.


//Using toFixed()

let num = 10.56789;
let result = num.toFixed(2);

console.log(result); // Output: 10.57

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

Note that toFixed() returns a string.

IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn’t work.

For instance:

2.005.toFixed(2) === "2.00"

Nowadays, you can use the Intl.NumberFormat constructor. It’s part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

const formatter = new Intl.NumberFormat('en-US', {
   minimumFractionDigits: 2,      
   maximumFractionDigits: 2,

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"

You can alternatively use the toLocaleString method, which internally will use the Intl API:

const format = (num, decimals) => num.toLocaleString('en-US', {
   minimumFractionDigits: 2,      
   maximumFractionDigits: 2,

console.log(format(2.005)); // "2.01"
console.log(format(1.345)); // "1.35"

This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.