;

How to Round Decimal Numbers in Javascript


Tutorialsrack 12/01/2022 Jquery Javascript

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;

Example 1: Using toFixed() Method

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.

Example 2: Using Math.Round() Method

The Math.round() function returns the value of a number rounded to the nearest integer. 

  • You can take the decimal number and add a very small number, Number.EPSILON, to ensure that the number rounding is accurate.
  • Then, you can multiply by number with 100 before rounding to extract only the 2 digits after the decimal place. Finally, we divide the number by 100 to get a max of 2 decimal places.

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.

Example 3: One More Better Approach to Round decimal Number

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!


Related Posts



Comments

Recent Posts
Tags