How to Format Number with Two Decimals

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 to.Fixed like this:

Javascript format number with two decimals
let num = 86.534572; console.log((Math.round(num * 100) / 100).toFixed(2));

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

Javascript format number with two decimals
var num1 = "1"; console.log((Math.round(num1 * 100) / 100).toFixed(2)); var num2 = "1.586"; console.log((Math.round(num2 * 100) / 100).toFixed(2)); var num3 = "1.756324"; console.log((Math.round(num3 * 100) / 100).toFixed(2));

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

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
console.log(Number(Math.round(1.005 + 'e2') + 'e-2').toFixed(2));

The Math.round() Method

The Math.round() 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 0.5, it will be rounded to the next integer in the direction of +∞.