JavaScript 格式化數字、金額、千分位、保留幾位小數、舍入舍去…

前端開發中常常會碰到用 JavaScript 格式化數字,最最多見的是格式化金額,通常格式化金額須要千分位分隔,保留2位小數等等。css

簡單的功能函數

相似的代碼網上有不少:前端

 

JavaScript 代碼:git

  1. /**
  2. * 將數值四捨五入(保留2位小數)後格式化成金額形式
  3. *
  4. * @param num 數值(Number或者String)
  5. * @return 金額格式的字符串,如'1,234,567.45'
  6. * @type String
  7. */
  8. function formatCurrency(num) {
  9. num = num.toString().replace(/\$|\,/g,'');
  10. if(isNaN(num))
  11. num = "0";
  12. sign = (num == (num = Math.abs(num)));
  13. num = Math.floor(num*100+0.50000000001);
  14. cents = num%100;
  15. num = Math.floor(num/100).toString();
  16. if(cents<10)
  17. cents = "0" + cents;
  18. for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
  19. num = num.substring(0,num.length-(4*i+3))+','+
  20. num.substring(num.length-(4*i+3));
  21. return (((sign)?'':'-') + num + '.' + cents);
  22. }

或者github

 

JavaScript 代碼:函數

  1. function fmoney(s, n) {
  2. /*
  3. * 參數說明:
  4. * s:要格式化的數字
  5. * n:保留幾位小數
  6. * */
  7. n = n > 0 && n <= 20 ? n : 2;
  8. s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  9. var l = s.split(".")[0].split("").reverse(),
  10. r = s.split(".")[1];
  11. t = "";
  12. for (i = 0; i < l.length; i++) {
  13. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  14. }
  15. return t.split("").reverse().join("") + "." + r;
  16. }
  17. //調用
  18. fmoney(9.7,2);//9.70
  19. 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

  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"

參數有點多,你能夠根據你本身的需求去修改。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

相關文章
相關標籤/搜索