How to round a number to 2 decimal places in JavaScript
In this article, we will show you how to round a number to 2 decimal places in JavaScript.
- How to select a random element from an array in JavaScript
- How to get the current URL using JavaScript
- Sorting an array in JavaScript
- How to convert an Array to a String in JavaScript
- How to convert a string to an integer 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..!!