JS四捨五入保留兩位小數
阿新 • • 發佈:2018-12-06
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 }