Code Premix

How to round a number to 2 decimal places in JavaScript

📅July 4, 2021
🗁JavaScript

In this article, we will show you how to round a number to 2 decimal places in JavaScript.

The toFixed() method is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal.

Example 1:

const number = 28.319921 
const rounded_number = number.toFixed(2)
// Output: 28.32

Here, .toFixed(2) method convert the 28.319921 number into number with only 2 decimal points.

Example 2:

const number = 28
const rounded_number = number.toFixed(3)
// Output: 28.000

The .toFixed(3) method keeping three decimals even though they’re zero.

Example 3:

Now, we will convert the number with decimal points to a rounded whole number. If we give a value of 0 to the .toFixed() method, it will round the whole number. Also If there is no parameter passed in the toFixed() method then it doesn’t display any digits after the decimal place.

const number = 28.319921
const rounded_number = number.toFixed(0)
// Output: 28

That’s it for today.
Thank you for reading. Happy Coding..!!