Only add thousand separator before decimal comma

丶灬走出姿态 提交于 2019-11-28 08:32:08

问题


I have found a regex on stackoverflow to add a ',' or '.' after every third number depending on your language.

(\d)(?=(\d\d\d)+(?!\d))

The problem is that it also happens when we reach the decimal point like with for example:

5487445.46878

The result of that with the following code (and regex) is:

return number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

Which results in:

5,487,445.46,878

I'm using this regex when I'm converting a number depending on your language. In Dutch for example a comma is used as a seperator, so there I do the following:

return number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")

Which results in

5.487.445,46.878

These of course need to become:

5,487,445.46878

and

5.487.445,4687

Does anybody know where I need to update the regex to ignore the decimal point?


回答1:


You can use your RegEx but split your number first if its has a comma or point in it.

jsFiddle demo

 var input = '5487445.46878';
 var parts = input.split('.');
 var part1 = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
 var part2 = parts[1];

 alert(part1 + '.' + part2);



回答2:


You can try this:-

    function thousandsSeparator(input) {
    var output = input
    if (parseFloat(input)) {
        input = new String(input);
        var parts = input.split("."); 
        parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
        output = parts.join(".");
    }

    return output;
}


来源:https://stackoverflow.com/questions/18513518/only-add-thousand-separator-before-decimal-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!