To format a floating-point number to 2 decimal places, you can use the Number.toFixed()
method. The toFixed()
method takes a single parameter which represents how many digits should appear after the decimal point of the number.
In our case, we want only two digits of the number after the decimal point, therefore, we have to pass 2 as a parameter to the toFixed()
method. The result of the toFixed()
method is a string representation of the number.
let num1 = 10.152714; console.log(num1.toFixed(2)); // 10.15 let num2 = 82; console.log(num2.toFixed(2)); // 82.00 let num3 = 15.2; console.log(num3.toFixed(2)); // 15.20 let num4 = 20.34; console.log(num4.toFixed(2)); // 20.34
The toFixed()
method can also round the number if necessary. It can also pad the number with zeros if necessary so that it can have the specified length after the fractional part of the number.
let num1 = 22.1492; console.log(num1.toFixed(2)); // 22.15 let num2 = 12.10591; console.log(num2.toFixed(2)); // 12.11 let num3 = 12; console.log(num3.toFixed(2)); // 12.00
The toFixed()
method returns a string representation of the number it formatted. So, if you want the result to be a number, you can use the parseFloat()
method.
See the following example:
let num1 = 22.51349; let result = num1.toFixed(2); console.log(result); // 22.51 console.log(typeof result); // string let numeric = parseFloat(result); console.log(numeric); // 22.51 console.log(typeof numeric); // number
Thanks for reading.