js将金额专成每隔3位数加逗号,比如 12345.00 转成 12,345.00;
懒得解释具体代码如下
1 //分割
2 String.prototype.joinByNum = function(num, deli){
3 (typeof num == 'undefined' || num == 0 || num == '' ) && (num = 3);
4 (typeof deli == 'undefined' || deli == '') && (deli = ',');
5 var oristr = this.toString().replace(/^\s*|\s*$|¥|,/g, ''),//去除了一些特殊符号以及空格
6 i = oristr.length - 1,
7 lastIndex = oristr.lastIndexOf('.'),
8 str = '',
9 index = 0;
10 if(isNaN(oristr)) return oristr;
11 (lastIndex !== -1) && (i = lastIndex - 1);
12 for (; i >= 0; i--) {
13 str = oristr[i] + str;
14 if ( i !== 0 && ++index % num === 0) {
15 str = deli + str;
16 }
17 }
18 str += lastIndex !== -1 ? (function(){
19 return Number(oristr.substr(lastIndex)).toFixed(2).substr(1);
20 })() : '.00';
21
22 return str;
23 };
24
25 //钱分割
26 Number.prototype.joinByNum = function(){
27 return ''.joinByNum.apply(''+ this, arguments);
28 };
测试结果:
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);
};