Method 1: Using the toFixed()
The “toFixed()” method accepts an argument that specifies the number of decimal places you want to round to and returns a “string” representing the rounded number.
const num = 3.141592; const roundedNum = num.toFixed(2); console.log(roundedNum);
In this code, the number 3.141592 is rounded to two decimal places using toFixed(2), resulting in the string ‘3.14’.
Remember that the “toFixed()” method returns a string, not a number. If you need the result as a number, you can convert it back to a number using “parseFloat()” or the “unary plus operator (+)”.
const num = 3.141592; const roundedNum = num.toFixed(2); const numAsFloat = parseFloat(roundedNum); console.log(numAsFloat); const numAsNumber = +roundedNum; console.log(numAsNumber);
Both parseFloat(roundedNum) and +roundedNum convert the rounded string to a number with the value 3.14.
Method 2: Using the Math.round()
To round a number to two decimal places using the “Math.round()” method, you can “multiply the number by 100, round it to the nearest integer, and divide the result by 100”. This process ensures you retain two decimal places in the final rounded number.
const num = 3.141592; const roundedNum = Math.round(num * 100) / 100; console.log(roundedNum);
In this code, we multiplied the number 3.141592 by 100, which resulted in 314.1592. Then, we used the “Math.round()” method to round this value to the nearest integer, 314. Finally, we divide the result by 100 to obtain the rounded number 3.14.
This approach works for rounding to two decimal places, but you can also adapt it to round to a different number of decimal places by adjusting the multiplier and divisor. For example, to round to three decimal places, you multiply and divide by 1000 instead of 100.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.