-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
正则如何给数字加上千位数分隔符号 #101
Comments
因为小数不需要分割符,所以想了一圈,没想到一个正则的解法,下面是两个正则的解法 function commafy(num) {
return num && num.toString().replace(/([+-]?)(\d+)([.]\d+)?/, function($0, $1, $2, $3) {
return $1 + $2.replace(/(\d)(?=(\d{3})+$)/g, function($10, $11) {
return $11 + ',';
}) + ($3 || '');
});
}
console.log(new Date().getTime()) console.log(commafy('+1234567.123456')) console.log(commafy('-123456.123456'));
console.log(commafy('56.123456'));
console.log(commafy('0.123456'));
console.log(commafy('123'));
console.log(commafy('1234'));
console.log(commafy('.12'));
console.log(new Date().getTime()); |
|
replace(/\B(?=(\d{3})+(?!\d))/g, ",") |
js本身就有自带千分位方法,何必自己写呢?数字直接调用toLocaleString()就行了。不过,这个方法只能精确到小数点后3位 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我的解法,。。。正则真心看不熟悉。。。还有就是原先的答案再没有小数的时候,不会有分隔符了。。bug,,而我的js函数结合正则可以规避这个bug,咳咳咳。。好吧,其实我根据运行前的时间戳和之后的时间戳相减,发现运行速度是一样的,原答案的解法更具hacking,好吧。真的好纠结不懂正则
The text was updated successfully, but these errors were encountered: