Home > Article > Web Front-end > How to keep two decimal places in javascript
Below we will introduce to you the implementation method of retaining two decimal places in JavaScript:
Rounding
The following processing results will be Rounding:
var num =2.446242342; num = num.toFixed(2); // 输出结果为 2.45
No rounding
The following processing results will not be rounded.
The first one, first convert the decimal into an integer:
Math.floor(15.7784514000 * 100) / 100 // 输出结果为 15.77
The second one, treat it as a string, use regular matching:
Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/)) // 输出结果为 15.77,不能用于整数如 10 必须写为10.0000
Note: If it is a negative number, please First convert it to a positive number and then calculate it, and finally convert it back to a negative number
Recommended: "javascript video tutorial"
The above is the detailed content of How to keep two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!