金额格式化js

1、有小数点的金额格式化

金额格式化:

 

/***
格式化
 *@params money {Number or String} 金额
	*@params digit {Number} 小数点的位数,不够补0
 *@returns {String} 格式化后的金额	  
**/
function formatMoney(money, digit){
var tpMoney = '0.00';
if(undefined != money){
    tpMoney = money;
}
tpMoney = new Number(tpMoney);
if(isNaN(tpMoney)){
  return '0.00';
}
tpMoney = tpMoney.toFixed(digit) + '';
var re = /^(-?\d+)(\d{3})(\.?\d*)/;
while(re.test(tpMoney)){
	 tpMoney = tpMoney.replace(re, "$1,$2$3")
	}
		
return tpMoney;
}

 反格式化金额:

 

 

function parseMoney(s, n) { 
	n = n > 0 && n <= 20 ? n : 2; 
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; 
	return s;
} 

 

 

2、不带小数点的金额

(1)格式化

 

function format(number) {   //format number like 100,000
     number = number.toString();
     var arrStr = number.split('.'),
         floatPart = arrStr[1],
         step = 3,
         len = 0;
     number = arrStr[0];
     len = number.length;
      
     if(len > step) {
         var c1 = len%step, 
             c2 = parseInt(len/step),
             arr = [],
             first = number.substr(0, c1);
         if(first != '') {
             arr.push(first);
         };
         for(var i=0; i<c2; i++) {
             arr.push(number.substr(c1 + i*step, step));                                     
         };
         number = arr.join(',');
     };
     return number + '.' + floatPart;
}

 (2)反格式化

 

function convertToNum(string) {  //convert String to Number
    return parseFloat(string.replace(/,/g, ''));
}

 

你可能感兴趣的:(格式化)