How to Round to at Most 2 Decimal Places in Javascript

Dec 15, 2023

2 mins read

Published in

Rounding numbers in JavaScript is a common task, especially when dealing with financial calculations or presenting data. In this blog post, we’ll explore how to round numbers to at most two decimal places in JavaScript and provide a concise code solution.

The Math.round() Method:

JavaScript provides the Math.round() method, which rounds a number to the nearest integer. To round a number to two decimal places, we can utilize this method along with multiplication and division. Here’s a simple function to achieve this:

1
2
3
4
5
6
7
8
function roundToTwoDecimalPlaces(number) {
    return Math.round(number * 100) / 100;
}

// Example Usage:
let originalNumber = 12.3456;
let roundedNumber = roundToTwoDecimalPlaces(originalNumber);
console.log(roundedNumber); // Output: 12.35

Explanation:

  1. Multiply the original number by 100 to shift the decimal point two places to the right.
  2. Use Math.round() to round the result to the nearest integer.
  3. Divide the rounded result by 100 to shift the decimal point back to its original position.

The toFixed() Method:

Another approach is to use the toFixed() method, which returns a string representing a number rounded to a specified number of decimal places:

1
2
3
4
5
6
7
8
function roundToTwoDecimalPlaces(number) {
    return parseFloat(number.toFixed(2));
}

// Example Usage:
let originalNumber = 12.3456;
let roundedNumber = roundToTwoDecimalPlaces(originalNumber);
console.log(roundedNumber); // Output: 12.35

a. Use toFixed(2) to round the number to two decimal places and convert it to a string.

b. Parse the string back to a float using parseFloat().

Rounding numbers to at most two decimal places in JavaScript can be achieved using either the Math.round() method along with multiplication and division or the toFixed() method. Choose the method that best fits your specific use case.

Sharing is caring!