Skip to content
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

Open
plh97 opened this issue Sep 22, 2017 · 4 comments
Open

正则如何给数字加上千位数分隔符号 #101

plh97 opened this issue Sep 22, 2017 · 4 comments

Comments

@plh97
Copy link

plh97 commented Sep 22, 2017

console.log(new** Date().getTime())
function commafy(num){
	return num && num
		.toString()
		.split(".")[0]
		.split("").reverse().join("")
		.replace(/(\d{3})/g, function($1, $2){
			return $2 + ',';
		}).split("").reverse().join("")+(num.split(".")[1] ? "."+num.split(".")[1] : '');
}
console.log(commafy('+1234567.123'))
console.log(new Date().getTime())

我的解法,。。。正则真心看不熟悉。。。还有就是原先的答案再没有小数的时候,不会有分隔符了。。bug,,而我的js函数结合正则可以规避这个bug,咳咳咳。。好吧,其实我根据运行前的时间戳和之后的时间戳相减,发现运行速度是一样的,原答案的解法更具hacking,好吧。真的好纠结不懂正则

@dailc
Copy link

dailc commented Sep 26, 2017

因为小数不需要分割符,所以想了一圈,没想到一个正则的解法,下面是两个正则的解法

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());

@mizi-lin
Copy link

mizi-lin commented Sep 27, 2017

var commafy  = function(str) {
            str = (+ str).toString();
            var reg = str.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
            return str.replace(reg, '$1,');
        }

@Barret-ma
Copy link

replace(/\B(?=(\d{3})+(?!\d))/g, ",")

@Pulset
Copy link

Pulset commented Jan 16, 2018

js本身就有自带千分位方法,何必自己写呢?数字直接调用toLocaleString()就行了。不过,这个方法只能精确到小数点后3位

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants