js将数字每3位之间用逗号分割

/**
 * 将数字每3位之间用逗号分割
 * 关注微信公众号wu7zhi,搜索大学课后习题答案
 * 
 */
function formatNum (number) {
var str = number.toString();
var newStr = "";
var count = 0;
if (str.indexOf(".") == -1) {
for (var i = str.length - 1; i >= 0; i--) {
if (count % 3 == 0 && count != 0 && str.charAt(i) != '-') {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr;
}
count++;
}
// 自动补小数点后两位
str = newStr + ".00";
return str;
} else {
for (var i = str.indexOf(".") - 1; i >= 0; i--) {
console.log(str.charAt(i));
if (count % 3 == 0 && count != 0 && str.charAt(i) != '-') {
newStr = str.charAt(i) + "," + newStr;
} else {
newStr = str.charAt(i) + newStr;
}
count++;
}
str = newStr + str.substr(str.indexOf("."), 3);
return str;
}
}

你可能感兴趣的:(JS库)