How to Round a Number to 2 Decimal Places in JavaScript
In JavaScript, you can use the toFixed()
method to round a number to a specified number of decimal places. Here’s an example:
let num = 3.14159;
let roundedNum = num.toFixed(2);
console.log(roundedNum); // Output: 3.14
In this example, the toFixed()
method is called on the num
variable with an argument of 2
, which specifies that the number should be rounded to 2 decimal places. The resulting value is stored in the roundedNum
variable, which is then logged to the console.
Note that the toFixed()
method returns a string, so if you need to perform further calculations with the rounded number, you may need to convert it back to a number using the parseFloat()
or Number()
function.