Round a Number to 1 Decimal Place in JavaScript


Borislav Hadzhiev

Sat Oct 23 20212 min read


Photo by Hannah Busing

Round a Number to 1 Decimal Place #

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

const num1 = 5.566; const result1 = num1.toFixed(1); console.log(result1); // 👉️ 5.6 console.log(typeof result1); // 👉️ string // 👇️ if the value is a string // call parseFloat to convert it to a number first const str1 = '5.666'; const result2 = parseFloat(str1).toFixed(1); console.log(result2); // 👉️ 5.7 console.log(typeof result2); // 👉️ string // 👇️ Convert string back to a number const num2 = 5.05; const result3 = Number(num2.toFixed(1)); console.log(result3); // 👉️ 5 console.log(typeof result3); // 👉️ number

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

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 our 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 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 5.00 is the same as 5, so the trailing zeros get dropped when the value is converted to a number.

console.log(5.00 === 5); // 👉️ true
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

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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.