Home > Web Front-end > JS Tutorial > body text

How to Format Floats with Precision in JavaScript?

Mary-Kate Olsen
Release: 2024-10-21 20:54:03
Original
947 people have browsed it

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);
Copy after login

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>
Copy after login

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);
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template