Created
May 29, 2014 06:00
-
-
Save leohxj/661f27257f72a80202cd to your computer and use it in GitHub Desktop.
将阿拉伯数字每三位分隔,如15000->15,000
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 直白一点的方法, 循环拼接字符串 | |
function formatNumber(number, split) { | |
var string = String(number); | |
var split = split || 3; | |
var newStr= new Array(string.length+ parseInt(string.length/split)); | |
newStr[newStr.length-1]=string[string.length-1]; | |
var currentIndex=string.length-1; | |
for(var i = newStr.length-1;i >= 0;i--) | |
{ | |
if((newStr.length-i)%(split+1)==0) | |
{ | |
newStr[i]=","; | |
} | |
else | |
{ | |
newStr[i]=string[currentIndex--]; | |
} | |
} | |
return newStr.join("") | |
} | |
// 直白2 | |
function formatNumber(number, split) { | |
var string = String(number); | |
var split = split || 3; | |
var rmb=''; | |
var i2=0; | |
for(var i=string.length-1; i>=0; i--){ | |
if(i%split==0&&i!=0){ | |
rmb+=string[i2]+','; | |
}else{ | |
rmb+=string[i2]; | |
} | |
i2++; | |
} | |
return rmb; | |
} | |
// 首先想到的是正则表达式,用到的正则为(/(\d{3})/g 或者 /(\d{3})(?=[^$])/g | |
function formatNumber(number, split) { | |
var string = String(number); | |
var split = split || 3; | |
// 注意这里,动态拼接正则的时候,注意转义字符 | |
var SplitReg = eval("/(\\d{"+split+"})/g"); | |
// var SplitReg = new RegExp("(\\d{"+split+"})", "g"); | |
// 正则对字符串是从左向右划分,需要注意反转 | |
return string.split("").reverse().join("").replace(SplitReg, "$1,").split("").reverse().join(""); | |
} | |
// 上面不严谨,还有直接使用的正则 | |
'1500000000000'.replace(/\B(?=(\d{3})+$)/g,','); | |
'1500000000000'.replace(/(?=(?!^)(?:\d{3})+(?:\.|$))(\d{3}(\.\d+$)?)/g,',$1'); | |
// 利用toLocaleString()方法 | |
15000000..toLocaleString(); | |
// 递归 | |
function formatNumber(number, split) { | |
number = String(number); | |
var split = split || 3; | |
if (number.length <= split) { | |
return number; | |
} else { | |
return formatNumber(number.substr(0, number.length - split) , split) + ',' + number.substr(number.length - split); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment