In this article, you’ll learn how to round decimal numbers in javascript. In Javascript, decimal numbers can be rounded using the Number.
toFixed()
method and Math.round()
method.
Let's say you have a decimal number like this.
const number = 467.8945645672283838;
The Number.toFixed()
method takes an integer as input and returns the number as a string. In Number.toFixed()
method, the parameter is optional, If you don't pass the parameter to toFixed()
method, then only the integer part of the number is returned without the decimal part.
You can round the number to 2 decimal places by providing 2 as the parameter to the toFixed()
method.
let number = 467.8945645672283838;
let num = Number(number.toFixed(2));
console.log(num);
// Output ==> 467.89
// Only 2 numbers after the decimal point is returned.
If you don't pass the parameter to the toFixed()
method, then only the integer part of the number is returned without the decimal part. Let’s take an example:
const number = 467.8945645672283838;
const num = Number(number.toFixed());
console.log(num);
// Output ==> 468
// Only Rounded Number is returned,
// No decimal part is returned.
The Math.round()
function returns the value of a number rounded to the nearest integer.
Number.EPSILON
, to ensure that the number rounding is accurate.Let’s take an example:
let number = 467.8945645672283838;
var rounded = Math.round((number + Number.EPSILON) * 100) / 100;
console.log(rounded);
// Output ==> 467.89
// Only 2 numbers after the decimal point is returned.
If you want 3 digits after the decimal place, then replace the 100 with 1000 in the above code and the above code will return a number with 3 digits after the decimal place.
The decimal rounding problem can be avoided by using numbers represented in exponential notation:
let number = 467.8945645672283838;
//Function To Round Decimal Number
//Parameters: num and decimals
//num ==> pass the Decimal Number,
//decimals == pass the digit you want round after decimal point
function roundDecimal(num, decimals) {
return Number(Math.round(num + "e" + decimals) + "e-" + decimals);
}
console.log(roundDecimal(number, 2));
// Output ==> 467.89
// Only 2 numbers after the decimal point is returned.
I hope this article will help you to understand how to round decimal numbers in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments