Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Arvin iuunhao
Added: Jun 18, 2018 9:02 AM
Views: 6
Tags: js
格式化金钱
  1. function number_format(number, decimals, dec_point, thousands_sep) {
  2.   /*
  3.   * 参数说明:
  4.   * number:要格式化的数字
  5.   * decimals:保留几位小数
  6.   * dec_point:小数点符号
  7.   * thousands_sep:千分位符号
  8.   * */
  9.   number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  10.   var n = !isFinite(+number) ? 0 : +number,
  11.     prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  12.     sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
  13.     dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  14.     s = '',
  15.     toFixedFix = function (n, prec) {
  16.       var k = Math.pow(10, prec);
  17.       return '' + Math.ceil(n * k) / k;
  18.     };
  19.  
  20.   s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  21.   var re = /(-?\d+)(\d{3})/;
  22.   while (re.test(s[0])) {
  23.     s[0] = s[0].replace(re, "$1" + sep + "$2");
  24.   }
  25.  
  26.   if ((s[1] || '').length < prec) {
  27.     s[1] = s[1] || '';
  28.     s[1] += new Array(prec - s[1].length + 1).join('0');
  29.   }
  30.   return s.join(dec);
  31. }