1 //四舍五入保留2位小数(若第二位小数为0,则保留一位小数)
2 function keepTwoDecimal(num) {
3 var result = parseFloat(num);
4 if (isNaN(result)) {
5 console.error('参数非数值,无法四舍五入保留两位小数!');
6 return false;
7 }
8 result = Math.round(num * 100) / 100;
9 return result;
10 }
11 //四舍五入保留2位小数(不够位数,则用0替补)
12 function keepTwoDecimalFull(num) {
13 var result = parseFloat(num);
14 if (isNaN(result)) {
15 console.error('参数非数值,无法四舍五入保留两位小数!');
16 return false;
17 }
18 result = Math.round(num * 100) / 100;
19 var s_x = result.toString();
20 var pos_decimal = s_x.indexOf('.');
21 if (pos_decimal < 0) {
22 pos_decimal = s_x.length;
23 s_x += '.';
24 }
25 while (s_x.length <= pos_decimal + 2) {
26 s_x += '0';
27 }
28 return s_x;
29 }
JS四舍五入保留两位小数
最新推荐文章于 2023-11-19 20:23:44 发布