Regular Expression for formatting numbers in JavaScript

前端 未结 14 1424
遥遥无期
遥遥无期 2020-11-30 19:35

I need to display a formatted number on a web page using JavaScript. I want to format it so that there are commas in the right places. How would I do this with a regular exp

相关标签:
14条回答
  • 2020-11-30 20:31

    Try something like this:

    function add_commas(numStr)
    {
        numStr += '';
        var x = numStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }
    
    0 讨论(0)
  • 2020-11-30 20:32

    I think you would necessarily have to do multiple passes to achieve this with regular expressions. Try the following:

    1. Run a regex for one digit followed by 3 digits.
    2. If that regex matches, replace it with the first digit, then a comma, then the next 3 digits.
    3. Repeat until (1) finds no matches.
    0 讨论(0)
提交回复
热议问题