Recently, I saw an interview (written test) question using js to implement the thousand-digit separator of numbers on the Internet, so I wrote a method that uses "regular + replace" to implement it:
The code copy is as follows:
var thousandsBitSeparator = function(numStr){
var b = /([-+]?/d{3})(?=/d)/g;
return numStr.replace(b, function($0, $1){
return $1 + ',';
});
}
Support matching of positive and negative signs and distinguishing decimal points. If there is any error, I hope everyone points out:-D
Attached a method of implementation by other netizens
The code copy is as follows:
<script language="JavaScript" type="text/javascript">
function formatNumber(num){
if(!/^(/+|-)?(/d+)(/./d+)?$/.test(num)){
return num;
}
var a = RegExp.$1,b = RegExp.$2,c = RegExp.$3;
var re = new RegExp().compile("(//d)(//d{3})(,|$)");
while(re.test(b)){
b = b.replace(re,"$1,$2$3");
}
return a +""+ b +""+ c;
}
var num=1234567/3;
alert("num="+num+", round: "+Math.round(num)+", two significant digits: "+num.toFixed(2)+", add thousand separator: "+formatNumber(num));
</script>
The above is all about this article, I hope you like it.