js将金额专成每隔3位数加逗号,比如 12345.00 转成 12,345.00;
懒得解释具体代码如下
//分割
String.prototype.joinByNum = function(num, deli){
(typeof num == 'undefined' || num == 0 || num == '' ) && (num = 3);
(typeof deli == 'undefined' || deli == '') && (deli = ',');
var oristr = this.toString().replace(/^\s*|\s*$|¥|,/g, ''),//去除了一些特殊符号以及空格
i = oristr.length - 1,
lastIndex = oristr.lastIndexOf('.'),
str = '',
index = 0;
if(isNaN(oristr)) return oristr;
(lastIndex !== -1) && (i = lastIndex - 1);
for (; i >= 0; i--) {
str = oristr[i] + str;
if ( i !== 0 && ++index % num === 0) {
str = deli + str;
}
}
str += lastIndex !== -1 ? (function(){
return Number(oristr.substr(lastIndex)).toFixed(2).substr(1);
})() : '.00'; return str;
}; //钱分割
Number.prototype.joinByNum = function(){
return ''.joinByNum.apply(''+ this, arguments);
};
测试结果:
old:789456123.22
new:789,456,123.22
old:10154344
new:10,154,344.00
貌似num里有个方法,所以又改了下。注意:这个toLocaleString貌似有点问题。比如safari就不会转。
//钱分割
Number.prototype.fomatMoney = function(){
var str = this.toLocaleString(),
arr = str.split('.');
if (arr.length < 2) {
str = arr[0]+ '.00';
}else{
str = arr[0] + Number(arr[1]).toFixed(2).substr(1);
}
return str;
};
//钱分割
String.prototype.fomatMoney = function(){
var oristr = this.toString();
if(oristr.indexOf(',') !== -1) return oristr;
return (0).fomatMoney.apply(Number(oristr), arguments);
};