"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Control Decimal Precision When Working with Floating-Point Numbers in JavaScript?

How to Control Decimal Precision When Working with Floating-Point Numbers in JavaScript?

Published on 2024-12-20
Browse:491

How to Control Decimal Precision When Working with Floating-Point Numbers in JavaScript?

Controlling Decimal Precision in JavaScript

When working with floating-point numbers in JavaScript, you may encounter situations where you need to control the number of digits displayed after the decimal point. For instance, you might want to display a price with only two decimal places.

Formatting a Float with Fixed Precision

To achieve this, JavaScript provides the toFixed() function. This function takes an argument that specifies the number of decimal places to keep. For example:

var x = 5.0364342423;
console.log(x.toFixed(2));

This code prints the value of x with only two decimal places, resulting in an output of 5.04.

Example: Formatting Currency

Let's consider the following currency value:

var price = 123.456789;

To format this value with two decimal places, we can use:

var formattedPrice = price.toFixed(2);

This assigns a formatted value of "123.45" to the variable formattedPrice.

Additional Notes

  • toFixed() returns a string representation of the formatted number.
  • If you provide a negative value as the argument, it represents the number of leading digits preserved before the decimal point (after rounding).
  • Alternatively, you can use the toLocaleString() function to format numbers based on the locale settings.
Release Statement This article is reprinted at: 1729514957 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3