Recent projects need our front end of the amount of the decimal format (that is, every three digits separated by commas), the code has been modified before the version is my negligence really sorry everyone! Now have made a change if there is not perfect place please advise!
1. Support comma separated by 0-9-bit comma
The JS code is as follows:
Copy Code code as follows:
/**
* JS format
* @param number to be formatted
* @param d [0-9] bit comma separated
*/
function Numformat (number,d) {
var numarrs = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '],
Reg_number =/^\d+ (. \d+)? $/;
D = d | | 3; No, it's 3位千.
if (isnumber) | | | isstring (number) | | Reg_number.test (number)) {
Convert first to String
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 ' number of incorrect incoming ';
}
}else if (prefix!= ' ' && suffix = = ') {
return prefix;
}else if (prefix = = ' && suffix!= ') {
prefix = 0;
return prefix + suffix;
}else {
Return "with Error";
}
}else {
Return ' incoming number to be formatted does not conform ';
}
}
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 another imperfect place that I call Console.log (Numformat ("1111.00")); Direct output of 1,111 on the console instead of 1,111.00 that is, if 0 is behind the decimal point, the Viewer will automatically erase the next 0 and the rest is normal! I tested the basic requirements of the following if there is an imperfect place please advise!