# Round a Number to 3 Decimal Places in JavaScript

Sat Oct 23 20212 min read

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
```Copied!```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
```Copied!```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
```Copied!```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.