Round a Number to 2 Decimal Places in JavaScript


Borislav Hadzhiev

Sat Oct 23 20212 min read


Photo by Greg Rakozy

Round a Number to 2 Decimal Places in JavaScript #

Use the toFixed() method to round a number to 2 decimal places, e.g. num.toFixed(2). The toFixed method formats a number to a specified number of decimal places and rounds the number if necessary.

const n1 = 13.5748; const r1 = n1.toFixed(2); console.log(r1); // ๐Ÿ‘‰๏ธ 13.57 console.log(typeof r1); // ๐Ÿ‘‰๏ธ string // ๐Ÿ‘‡๏ธ if the value is a string // call parseFloat to convert it to a number first const s1 = '13.5758'; const r2 = parseFloat(s1).toFixed(2); console.log(r2); // ๐Ÿ‘‰๏ธ 13.58 console.log(typeof r2); // ๐Ÿ‘‰๏ธ string // ๐Ÿ‘‡๏ธ Convert string back to a number const n2 = 13.1999; const r3 = Number(n2.toFixed(2)); console.log(r3); // ๐Ÿ‘‰๏ธ 13.2 console.log(typeof r3); // ๐Ÿ‘‰๏ธ number

In our first example, we used the Number.toFixed method to round a number to 2 decimal places.

The only parameter the method takes is the number of digits to appear after the decimal point.

The toFixed method returns a string representation of the number.

In our second example, we have a string that is a valid number. We had to call the parseFloat function on it, because the toFixed method can only be called on numbers.

In our third example, we used the the Number object to turn the string that the toFixed method returns into a number.

However, notice that the trailing zero was removed. When you convert a string with trailing zeros to a number in JavaScript, none of the trailing zeros are kept.

The number 1.00 is the same as 1, so the trailing zeros get dropped when the value is converted to a number.

Floating point numbers don't represent all decimals precisely in binary, which can lead to inconsistent results.
console.log(0.1 + 0.2 === 0.3); // ๐Ÿ‘‰๏ธ false const n1 = (13.555).toFixed(2); console.log(n1); // ๐Ÿ‘‰๏ธ 13.55 const n2 = (13.5551).toFixed(2); console.log(n2); // ๐Ÿ‘‰๏ธ 13.56

In the first example 0.1 + 0.2 equals 0.30000000000000004 instead of 0.3. This is because the binary floating-point format cannot accurately represent numbers like 0.1 or 0.2.

The code gets rounded to the nearest number, resulting in a rounding error.

In our second example, we would expect to get 13.56 back, but instead the number gets rounded down to 13.55.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee