Regular Expression for formatting numbers in JavaScript

前端 未结 14 1477
遥遥无期
遥遥无期 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:09

    If you really want a regex, you can use two in a while loop:

    while(num.match(/\d{4}/)) {
        num = num.replace(/(\d{3})(,\d|$)/, ',$1$2');
    }
    

    And if you want to be fancy, you can format numbers with decimal points too:

    while(num.match(/\d{4}(\,|\.)/)) {
        num = num.replace(/(\d{3})(,\d|$|\.)/, ',$1$2');
    }
    

    Edit:

    You can also do this with 2 regular expressions and no loop, splits, joins, etc:

    num = num.replace(/(\d{1,2}?)((\d{3})+)$/, "$1,$2");
    num = num.replace(/(\d{3})(?=\d)/g, "$1,");
    

    The first regex puts a comma after the first 1 or 2 digits if the remaining number of digits is divisible by three. The second regex places a comma after every remaining group of 3 digits.

    These won't work with decimals, but they work great for positive and negative integers.

    Test output:

    45
    3,856
    398,868,483,992
    
    635
    12,358,717,859,918,856
    -1,388,488,184
    

提交回复
热议问题