Home  >  Article  >  Web Front-end  >  How to Format Floats with Precision in JavaScript?

How to Format Floats with Precision in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 20:54:03868browse

How to Format Floats with Precision in JavaScript?

Formatting Floats with Precision

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.

Use toFixed() for Precision

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.

Example

Running the following code

<code class="javascript">console.log(formattedNum);</code>

will print 5.04.

Note for Scientific Notation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn