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.
To achieve this, JavaScript provides the toFixed() function. This function takes an argument that specifies the number of decimal places to keep. For example:
<code class="javascript">var x = 5.0364342423; console.log(x.toFixed(2));</code>
This code prints the value of x with only two decimal places, resulting in an output of 5.04.
Let's consider the following currency value:
<code class="javascript">var price = 123.456789;</code>
To format this value with two decimal places, we can use:
<code class="javascript">var formattedPrice = price.toFixed(2);</code>
This assigns a formatted value of "123.45" to the variable formattedPrice.
The above is the detailed content of How to Control Decimal Precision When Working with Floating-Point Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!