Skip to content

Instantly share code, notes, and snippets.

@pygman
Created September 2, 2016 09:34
Show Gist options
  • Save pygman/03c92f58005b2849c1fc18495f3cbd59 to your computer and use it in GitHub Desktop.
Save pygman/03c92f58005b2849c1fc18495f3cbd59 to your computer and use it in GitHub Desktop.
JavaScript处理数字分位符号
//数组方式处理 小数位有空格隔开
function addCommas(val) {
var aIntNum = val.toString().split(".");
if (aIntNum[0].length >= 5) {
aIntNum[0] = aIntNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (aIntNum[1] && aIntNum[1] >= 5) {
aIntNum[1] = aIntNum[1] ? aIntNum[1].replace(/\B(?=(\d{3})+(?!\d))/g, " ") : " ";
}
return aIntNum.join(".");
}
//字符串方式处理一
function addCommas(val) {
var sIntNum = val.toString(),
bIndex = sIntNum.indexOf('.');
return sIntNum.replace(/\d(?=(?:\d{3})+(?:\.|$))/g, function($0, i) {
return bIndex < 0 || i < bIndex ? ($0 + ',') : $0;
});
}
//字符串方式处理二
function addCommas(val) {
return (val + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment