A recent project requires us to format the amount in thousandths on the front end (that is, separate every three digits with commas). The code has been modified. The previous version was due to my negligence. I really feel sorry for everyone! It has been modified now. If there are still imperfections, please give me your advice!
1. Supports comma-separated 0-9 digits separated by commas.
The JS code is as follows:
Copy the code code as follows:
/**
*JS formatting
* @param number The number to be formatted
* @param d [0-9] separated by commas
*/
function numFormat(number,d) {
var numArrs = ['0','1','2','3','4','5','6','7','8','9'],
REG_NUMBER = /^/d+(./d+)?$/;
d = d || 3; // If not passed, it is 3 digits of thousandths.
if(isNumber(number) || isString(number) || REG_NUMBER.test(number)) {
//Convert to string first
var toString = number + '',
isPoint = toString.indexOf('.'),
prefix, // prefix
suffix, // 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 'How many digits passed in are incorrect';
}
}else if(prefix != '' && suffix == ''){
return prefix;
}else if(prefix == '' && suffix != ''){
prefix = 0;
return prefix + suffix;
}else {
return "There is an error";
}
}else {
return 'The number passed in to be formatted does not comply';
}
}
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")); and it directly outputs 1,111 instead of 1,111.00 on the console. In other words, if the decimal point is 0, the browser will automatically erase it. Drop the last 0 and everything else is normal! I have tested it and it basically meets the requirements. If there are any imperfections, please give me your advice!