In JavaScript, it is often necessary to convert floats to strings. However, by default, the string representation may include unnecessary decimal places. To control the number of decimal places, we need to use the toFixed() function.
To format a float with just 2 digits after the decimal point, use the following syntax:
var num = 5.0364342423; var formattedNum = num.toFixed(2);
Here, num is the original float, and toFixed() rounds it to two decimal places. The result is stored in formattedNum.
Running the following code
<code class="javascript">console.log(formattedNum);</code>
will print 5.04.
For floats in scientific notation, toFixed() rounds the decimal part of the mantissa to the specified precision. For example:
var num = 0.00003579; var formattedNum = num.toFixed(2);
Will print 0.000036.
The above is the detailed content of How to Format Floats with Precision in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!