Round a Number to 3 Decimal Places in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Wil Stewart

Round a Number to 3 Decimal Places #

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

index.js
const num1 = 7.456677; const result1 = num1.toFixed(3); console.log(result1); // ๐Ÿ‘‰๏ธ 7.457 console.log(typeof result1); // ๐Ÿ‘‰๏ธ string // ๐Ÿ‘‡๏ธ if the value is a string // call parseFloat to convert it to a number first const str1 = '7.456677'; const result2 = parseFloat(str1).toFixed(3); console.log(result2); // ๐Ÿ‘‰๏ธ 5.457 console.log(typeof result2); // ๐Ÿ‘‰๏ธ string // ๐Ÿ‘‡๏ธ Convert string back to a number const num2 = 7.79999999; const result3 = Number(num2.toFixed(3)); console.log(result3); // ๐Ÿ‘‰๏ธ 7.8 console.log(typeof result3); // ๐Ÿ‘‰๏ธ number

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

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

The toFixed method returns a string representation of the number.

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

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

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

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

index.js
console.log(7.000 === 7); // ๐Ÿ‘‰๏ธ true
Floating point numbers don't represent all decimals precisely in binary, which can lead to inconsistent results.
index.js
console.log(0.1 + 0.2 === 0.3); // ๐Ÿ‘‰๏ธ false

The sum of 0.1 and 0.2 is actually equal to 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.

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