In JavaScript, you can use the toFixed() method to retain two decimal places. The function of this method is to round the value to a number with specified decimal places. When the parameter is set to "2", the result returned Two decimal places of the specified value will be retained, and the syntax is "value.toFixed(2)".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
What is the method to retain two decimal places in JavaScript
The toFixed() method can round Number to a number with specified decimal places.
The syntax is:
number.toFixed(x)
where x is required. Specifies the number of decimal places, which is a value between 0 and 20, inclusive. Some implementations can support a larger range of values. If this parameter is omitted, 0 will be used instead.
The returned result has a fixed number of x digits after the decimal point.
The example is as follows:
<html> <head> <meta charset="utf-8"> <title>123</title> </head> <body> <p id="demo">单击按钮显示保留小数的数值</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var num = 5.56789; var x = document.getElementById("demo"); x.innerHTML=num.toFixed(2); } </script> </body> </html>
Output result:
The above is the detailed content of What is the way to keep two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!