round number to 2 decimal in javascript

To round a number to 2 decimal places in javascript, we can use the toFixed() method. The toFixed() method converts a number into a string, rounding to a specified number of decimal places.

Here's an example:

index.tsx
let num = 3.14159;
let roundedNum = num.toFixed(2); // returns "3.14"
70 chars
3 lines

In the code above, we first define a number num with more than 2 decimal places. We then call the toFixed(2) method on the num variable, which returns a string representation of the number with 2 decimal places rounded.

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 parseFloat() or Number().

gistlibby LogSnag