JavaScript 格式化数字 - 转
1 function number_format(number, decimals, dec_point, thousands_sep,roundtag) { 2 /* 3 * 参数说明: 4 * number:要格式化的数字 5 * decimals:保留几位小数 6 * dec_point:小数点符号 7 * thousands_sep:千分位符号 8 * roundtag:舍入参数,默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入 9 * */ 10 number = (number + '').replace(/[^0-9+-Ee.]/g, ''); 11 roundtag = roundtag || "ceil"; //"ceil","floor","round" 12 var n = !isFinite(+number) ? 0 : +number, 13 prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), 14 sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, 15 dec = (typeof dec_point === 'undefined') ? '.' : dec_point, 16 s = '', 17 toFixedFix = function (n, prec) { 18 19 var k = Math.pow(10, prec); 20 console.log(); 21 22 return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k; 23 }; 24 s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); 25 var re = /(-?\d+)(\d{3})/; 26 while (re.test(s[0])) { 27 s[0] = s[0].replace(re, "$1" + sep + "$2"); 28 } 29 30 if ((s[1] || '').length < prec) { 31 s[1] = s[1] || ''; 32 s[1] += new Array(prec - s[1].length + 1).join('0'); 33 } 34 return s.join(dec); 35 } 36 console.log(number_format(2, 2, ".", ","))//"2.00" 37 console.log(number_format(3.7, 2, ".", ","))//"3.70" 38 console.log(number_format(3, 0, ".", ",")) //"3" 39 console.log(number_format(9.0312, 2, ".", ","))//"9.03" 40 console.log(number_format(9.00, 2, ".", ","))//"9.00" 41 console.log(number_format(39.715001, 2, ".", ",", "floor")) //"39.71" 42 console.log(number_format(9.7, 2, ".", ","))//"9.70" 43 console.log(number_format(39.7, 2, ".", ","))//"39.70" 44 console.log(number_format(9.70001, 2, ".", ","))//"9.71" 45 console.log(number_format(39.70001, 2, ".", ","))//"39.71" 46 console.log(number_format(9996.03, 2, ".", ","))//"9996.03" 47 console.log(number_format(1.797, 3, ".", ",", "floor"))//"1.797"
KidYang