Implementation method: 1. Use the "/" operator to perform division operation, the syntax is "value 1 / value 2"; 2. Use "result of division operation.toFixed(2)" or "Math.floor( The result of the division operation *100)/100" statement to retain two decimal places.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
javascript implements division with two decimal places
can be divided into two parts:
Divide two numbers: You can use the "/
" operator to perform division operations
Retain two decimal places
General In terms of retaining two decimal places, you can use the following three methods:
1. Directly use the method toFixed(n) that comes with the numeric type, where the parameter is the number of digits that need to be retained. This The result of the conversion is character type.
var a=10; var b=3; var c=a/b; console.log("两数相除的结果:"+c); console.log("保留两位小数:"+c.toFixed(2));
#2. Combined with Math.floor(), use the method of multiplying first and then dividing. For example, if you want to keep two decimal places, Math.floor(c*100)/100 , if you want to keep three decimal places, then it is Math.floor(c*1000)/1000.
var a=10; var b=3; var c=a/b; console.log("两数相除的结果:"+c); console.log("保留两位小数:"+Math.floor(c*100)/100); console.log("保留三位小数:"+Math.floor(c*1000)/1000);
Using this method of multiplying first and then dividing is the most common method.
3. Use regular expressions to intercept. Here you need to test your regular skills.
var a=10; var b=3; var c=a/b; console.log("两数相除的结果:"+c); console.log("保留两位小数:"+c.toString().match(new RegExp(/^\d+(?:\.\d{0,2})?/)));
【Related recommendations: javascript learning tutorial】
The above is the detailed content of How to implement division with two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!