前端開發中常常會碰到用 JavaScript 格式化數字,最最多見的是格式化金額,通常格式化金額須要千分位分隔,保留2位小數等等。css
簡單的功能函數
相似的代碼網上有不少:前端
JavaScript 代碼:git
- /**
- * 將數值四捨五入(保留2位小數)後格式化成金額形式
- *
- * @param num 數值(Number或者String)
- * @return 金額格式的字符串,如'1,234,567.45'
- * @type String
- */
- function formatCurrency(num) {
- num = num.toString().replace(/\$|\,/g,'');
- if(isNaN(num))
- num = "0";
- sign = (num == (num = Math.abs(num)));
- num = Math.floor(num*100+0.50000000001);
- cents = num%100;
- num = Math.floor(num/100).toString();
- if(cents<10)
- cents = "0" + cents;
- for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
- num = num.substring(0,num.length-(4*i+3))+','+
- num.substring(num.length-(4*i+3));
- return (((sign)?'':'-') + num + '.' + cents);
- }
或者github
JavaScript 代碼:函數
- function fmoney(s, n) {
- /*
- * 參數說明:
- * s:要格式化的數字
- * n:保留幾位小數
- * */
- n = n > 0 && n <= 20 ? n : 2;
- s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
- var l = s.split(".")[0].split("").reverse(),
- r = s.split(".")[1];
- t = "";
- for (i = 0; i < l.length; i++) {
- t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
- }
- return t.split("").reverse().join("") + "." + r;
- }
- //調用
- fmoney(9.7,2);//9.70
- fmoney('12345.675910', 3);//12,345.676
更加完善的功能函數
這些代碼基本能很好的運行。不過關係到經濟利益的時候,還要考慮捨去或者舍入幾釐。你們懂的,每一個用戶幾釐錢可能帶來巨大的經濟收益。就好比說收手續費,若是一筆手續費計算出來是 3.4521
元,精確到分通常都會收 3.46
元。固然若是是付出去,那可能就是直接捨去了,通常會計算爲 3.45
元。spa
之前收集過相似方法,http://www.css88.com/archives/5307,不過在使用的時候會有BUG,JS 浮點型計算的精度問題。因此抽時間修復了一下:.net
JavaScript 代碼:code
- function number_format(number, decimals, dec_point, thousands_sep,roundtag) {
- /*
- * 參數說明:
- * number:要格式化的數字
- * decimals:保留幾位小數
- * dec_point:小數點符號
- * thousands_sep:千分位符號
- * roundtag:舍入參數,默認 "ceil" 向上取,"floor"向下取,"round" 四捨五入
- * */
- number = (number + '').replace(/[^0-9+-Ee.]/g, '');
- roundtag = roundtag || "ceil"; //"ceil","floor","round"
- var n = !isFinite(+number) ? 0 : +number,
- prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
- sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
- dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
- s = '',
- toFixedFix = function (n, prec) {
-
- var k = Math.pow(10, prec);
- console.log();
-
- return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k;
- };
- s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
- var re = /(-?\d+)(\d{3})/;
- while (re.test(s[0])) {
- s[0] = s[0].replace(re, "$1" + sep + "$2");
- }
-
- if ((s[1] || '').length < prec) {
- s[1] = s[1] || '';
- s[1] += new Array(prec - s[1].length + 1).join('0');
- }
- return s.join(dec);
- }
- console.log(number_format(2, 2, ".", ","))//"2.00"
- console.log(number_format(3.7, 2, ".", ","))//"3.70"
- console.log(number_format(3, 0, ".", ",")) //"3"
- console.log(number_format(9.0312, 2, ".", ","))//"9.03"
- console.log(number_format(9.00, 2, ".", ","))//"9.00"
- console.log(number_format(39.715001, 2, ".", ",", "floor")) //"39.71"
- console.log(number_format(9.7, 2, ".", ","))//"9.70"
- console.log(number_format(39.7, 2, ".", ","))//"39.70"
- console.log(number_format(9.70001, 2, ".", ","))//"9.71"
- console.log(number_format(39.70001, 2, ".", ","))//"39.71"
- console.log(number_format(9996.03, 2, ".", ","))//"9996.03"
- console.log(number_format(1.797, 3, ".", ",", "floor"))//"1.797"
參數有點多,你能夠根據你本身的需求去修改。orm
推薦的類庫 Numeral.js 和 accounting.js
Numeral.js
一個用於格式化和操做數字的JavaScript庫。數字能夠被格式化爲貨幣,百分比,時間,幾個小數位數,千分位等等。 您也能夠隨時建立自定義格式。ip
官網及文檔:http://numeraljs.com/
GitHub:https://github.com/adamwdraper/Numeral-js
accounting.js
一個輕量級的JavaScript庫,用於格式化數字,金額和貨幣等。
官網及文檔:http://openexchangerates.github.io/accounting.js/
GitHub:accounting.js