Recently working on a project requires our front-end to format the amount in thousandths (that is, every three digits are separated by commas). The code has been modified. The previous version was due to my negligence. I am really sorry for everyone! It has been modified now. If there are still some imperfections, please give me your advice!
1. Supports 0-9 characters separated by commas
The JS code is as follows:
if(isNumber(number) || isString(number) || REG_NUMBER.test(number)) {
// 先转换成字符串
var toString = number + '',
isPoint = toString.indexOf('.'),
prefix, // 前缀
suffix, // 后缀
t = '';
if(isPoint > 0) {
prefix = toString.substring(0,isPoint);
suffix = toString.substring(isPoint + 1);
}else if(isPoint == 0) {
prefix = '';
suffix = toString.substring(1);
}else {
prefix = toString;
suffix = '';
}
if(prefix != '') {
prefixArr = prefix.split('').reverse();
var isArrayIndex = isArray(d,numArrs);
if(isArrayIndex > -1) {
for(var i = 0, ilen = prefixArr.length; i < ilen; i =1) {
t = prefixArr[i] ((i 1) % isArrayIndex == 0 && (i 1) != prefixArr.length ? "," : "");
}
t = t.split("").reverse().join("");
if(suffix != '') {
return t "." suffix;
}else {
return t;
}
}else {
return '传入的多少位不正确';
}
}else if(prefix != '' && suffix == ''){
return prefix;
}else if(prefix == '' && suffix != ''){
prefix = 0;
return prefix suffix;
}else {
return "有错误";
}
}else {
return '传入的要格式化的数字不符合';
}
}
function isArray(item,arrs) {
for(var i = 0, ilen = arrs.length; i < ilen; i ) {
if(item == arrs[i]) {
return i;
}
}
return -1;
}
function isNumber(number) {
return Object.prototype.toString.apply(number) === '[object Number]';
}
function isString(number) {
return Object.prototype.toString.apply(number) === ['object String'];
}
But there seems to be an imperfection. I call console.log(numFormat("1111.00")); directly output 1,111 on the console instead of 1,111.00. In other words, if the decimal point is 0, the browser The following 0 will be automatically erased and everything else is normal! I tested it and it basically meets the requirements. If there are any imperfections, please give me your advice!