In the project encountered need to convert a number similar to the ' 450000 ' to accounting for the format used, ' 450,000.00 ', separating the Thousand and the decimal point after the two digits are not enough to automatically fill, has been recorded in several ways to achieve
PS: If you do not consider the following decimal point, the quickest way:
"12345678". Replace (/[0-9]+? =(?:( [0-9] {3})) +$)/g,function (a) {return + ', '}); Output 12 345 678
1. Implemented in a circular manner
function Formatnum (str) {
var newstr = "";
var count = 0;
if (Str.indexof (".") ==-1) {for
(var i=str.length-1;i>=0;i--) {
if (count% 3 = 0 && count!= 0) {
newstr = Str.charat (i) + "," + Newstr;
} else{
newstr = Str.charat (i) + newstr;
}
count++;
}
str = newstr + ". 00"; Two-bit
console.log (str)
}
else
{for
(var i = Str.indexof (".") after the decimal point is automatically filled -1;i>=0;i--) {
if (count% 3 = 0 && count!= 0) {
newstr = Str.charat (i) + "," + newstr;//hit a multiple of 3 plus "," Number
}else{
newstr = Str.charat (i) + newstr;//character story pick up
}
count++;
str = newstr + (str + "+"). substr ((str + ")" IndexOf ("."), 3);
Console.log (str)
}
}
formatnum (' 13213.24 ');//Output 13,213.34
formatnum (' 132134.2 ');//Output 132, 134.20
formatnum (' 132134 ');//Output 132,134.00
formatnum (' 132134.236 ');//Output 132,134.236
2. Use regular (relatively insufficient is still have to judge the number of digits after the decimal point, there are more intelligent regular please notify me ~)
function Regexnum (str) {
var regex =/(\d) (? = (\d\d\d) + (?!) \d))/g;
if (Str.indexof (".") = = 1) {
str= str.replace (Regex, ', ') + '.
Console.log (str)
}else{
var newstr = Str.split ('. ');
var str_2 = newstr[0].replace (Regex, ', ');
if (newstr[1].length <= 1) {
//Only one time after the decimal point
str_2 = str_2 + '. ' + newstr[1] + ' 0 ';
Console.log (str_2)
}else if (Newstr[1].length > 1) {
//decimal point after two digits
var decimals = newstr[1].substr (0,2 );
var srt_3 = str_2 + '. ' + decimals;
Console.log (Srt_3)}}
;
Regexnum (' 23424224 '); Output 2,42,224.00
regexnum (' 23424224.2 ');//Output 2,42,224.20
regexnum (' 23424224.22 ');//Output 2,42,224.22
Regexnum (' 23424224.233 '); Output 2,42,224.23
The above is the entire contents of this article, learn more JavaScript syntax, you can see: "JavaScript Reference tutorial", "JavaScript Code style guide," And I hope that we support the cloud-Habitat community.