Home > Article > Web Front-end > How to get two decimal places after division in jquery
Method: 1. Use the toFixed() method to take the two decimal places. This method can round the decimal to the specified number of digits. The syntax is "division result.toFixed(2)"; 2. Use round() The method takes two decimal places, and the syntax is "Math.round(division result*100)/100".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
How to get two decimal places after division in jquery
1. The toFixed() method can round Number to a number with specified decimal places. .
Syntax
NumberObject.toFixed(num)
num 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.
Return value
Returns the string representation of NumberObject, which does not use exponential counting and has a fixed num digits after the decimal point. The number is rounded if necessary and padded with zeros so that it reaches the specified length. If num is greater than le 21, this method simply calls NumberObject.toString(), returning a string in exponential notation.
The example is as follows:
<html> <body> <p id="demo"></p> <script> var x = 7; var y = 8; var z = x / y; var result =z.toFixed(2); document.getElementById("demo").innerHTML = result; </script> </body> </html>
Output result:
2. The round() method can round a number to The nearest integer.
Syntax
Math.round(x)
x Required. Must be a number.
Return value
The integer closest to x.
Explanation
For 0.5, this method will round up.
For example, 3.5 will be rounded to 4, and -3.5 will be rounded to -3.
The example is as follows:
<html> <body> <p id="demo"></p> <script> var x = 7; var y = 8; var z = x / y; var result =Math.round(z*100)/100; document.getElementById("demo").innerHTML = result; </script> </body> </html>
Output result:
Related video tutorial recommendation: jQuery video tutorial
The above is the detailed content of How to get two decimal places after division in jquery. For more information, please follow other related articles on the PHP Chinese website!