I guess you want to realize the digit display of numbers. You want "12345" to be displayed as "12,345" instead of "123,45". Some people got it wrong. The solution given by some people is that the number "123456" will be output as ",123,456", which obviously has an extra comma. My method will not have this problem.
1L's answer (use NumberObject.toLocaleString(), convert the numbers to strings, and use the local number format sequence.) can solve the problem, but it is not recommended because it depends on your local preferences and the results may be different for different people.
Someone asked this question a few days ago /q/10... However, the above method is not suitable for decimal points. Since js does not support reverse pre-checking, use another set of regular rules for decimal points.
comdify : function (n){
var re=/\d{1,3}(?=(\d{3})+$)/g;
var n1 = String(n).replace(/^(\d+)((\.\d+)?)$/,function(s,s1,s2){return s1.replace(re,"$&,")+s2;});
return n1;
}
There is a super simple method 234234..toLocaleString()
I guess you want to realize the digit display of numbers. You want "12345" to be displayed as "12,345" instead of "123,45". Some people got it wrong.
The solution given by some people is that the number "123456" will be output as ",123,456", which obviously has an extra comma. My method will not have this problem.
1L's answer (use
NumberObject.toLocaleString()
, convert the numbers to strings, and use the local number format sequence.) can solve the problem, but it is not recommended because it depends on your local preferences and the results may be different for different people.Implemented in a non-recursive way
Also supports decimal points!
Recursively implemented
This question requires recursive implementation, so the answer also provides recursive implementation.
The one upstairs is better
The shortest code is here, let’s see if there is any shorter one.
From left to right
From right to left
Someone asked this question a few days ago /q/10...
However, the above method is not suitable for decimal points. Since js does not support reverse pre-checking, use another set of regular rules for decimal points.
And what the hell is recursion? You don’t need to use recursion for this, right?