W3docs

How to Format Number with Two Decimals

In this JavaScript tutorial, you will find information about the formatting number to display with two decimals. Also, read about solving rounding issues.

This tutorial provides information about the formatting numbers always to display 2 decimal places and round them where applicable. All you need is the JavaScript built-in Math.round method. Here are two approaches.

You can use toFixed like this:

Javascript format number with two decimals

javascript— editable

Here is the full example of numbers in 2 decimal place format:

Javascript format number with two decimals

javascript— editable

However, this will fail if the value is 1.005. To solve this rounding issue, you can use numbers represented in exponential notation:

Javascript format number with two decimals

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

Try the example and see how the given code will solve the problem of rounding:

Javascript format number with two decimals

javascript— editable

The Math.round() Method

The <kbd class="highlighted">Math.round()</kbd> function will return the value of a number rounded to the nearest integer. If the argument's fractional portion is greater than 0.5, the argument will be rounded with the next higher absolute value. If the argument is less than 0.5, it will be rounded with the lower absolute value. If the fractional portion is exactly 0.5, it rounds toward positive infinity (e.g., 1.5 becomes 2, -1.5 becomes -1).