Round a Number to Decimal Points in JavaScript
Today we decided to write a simple article on how to round a number to decimal points in JavaScript.
Round a Number to Decimal Points in JavaScript, Round off a number upto two decimal place using JavaScript, JavaScript toFixed(), Round to at most 2 decimal places, Rounding Decimals How to Round Numbers, Round a Number to Decimal Points, HowTo: round a number up to N decimal digits, javascript format number 2 decimals, JavaScript limit input to 2 decimal places, html number format decimal places, javascript tofixed without rounding.
Checkout more articles on JavaScript
- url-in-javascript" title="Get Current URL in JavaScript">Get Current URL in JavaScript
- array-methods-in-javascript" title="Push, Pop, Shift and Unshift Array Methods in JavaScript">Push, Pop, Shift and Unshift Array Methods in JavaScript
- Arrow Functions in JavaScript
- string-javascript" title="Replace all occurrences of a string in JavaScript">Replace all occurrences of a string in JavaScript
- Compare two dates in JavaScript
Use the `toFixed()` method to round a number to decimal place in JavaScript. The toFixed() method is used to return a string representation of a number of digits after the decimal point.
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.
Thanks for reading and happy coding!