Below we will introduce methods for retaining two decimal places in JavaScript:
Rounding
The following processing results will be rounded:
var num =2.446242342; num = num.toFixed(2); // 输出结果为 2.45
Without Rounding
The following processing results will not be rounded.
First method, convert the decimal to an integer first:
Math.floor(15.7784514000 * 100) / 100 // 输出结果为 15.77
Second method, treat it as a string and use regular expression matching:
Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/)) // 输出结果为 15.77,不能用于整数如 10 必须写为10.0000
Note:If it is a negative number, please convert it to a positive number first, then calculate, and finally convert it back to a negative number.