W3docs

How to Format a Number with Two Decimals in JavaScript

Read this JavaScript tutorial and learn useful information about several easy built-in methods that are used for formatting the number with two decimals.

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 <kbd class="highlighted">Intl.NumberFormat</kbd> constructor. It is supported in major browsers and in Node.js:

Javascript Intl.NumberFormat constructor

javascript— editable

toLocaleString

The alternative of the above method is the <kbd class="highlighted">toLocaleString</kbd> method which internally uses the Intl API:

Javascript toLocaleString method

javascript— editable

toFixed

One of the methods used is the <kbd class="highlighted">toFixed</kbd> method which returns a string:

Javascript toFixed method

javascript— editable
Warning

The <kbd class="highlighted">toFixed()</kbd> method can produce unexpected results due to IEEE 754 floating-point representation.

For example:

Javascript toFixed method

javascript— editable

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

javascript— editable

For production code, prefer <kbd class="highlighted">Intl.NumberFormat</kbd> or <kbd class="highlighted">toLocaleString</kbd> as they handle locale-specific formatting and rounding rules more reliably than <kbd class="highlighted">toFixed</kbd>.