Regular Expression for formatting numbers in JavaScript

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

    With the caveat that Intl.NumberFormat and Number.toLocaleString() are now there for this purpose in JavaScript:

    The other answers using regular expressions all break down for decimal numbers (although the authors seem to not know this because they have only tested with 1 or 2 decimal places). This is because without lookbehind, JS regular expressions have no way to know whether you are working with the block of digits before or after the decimal point. That leaves two ways to address this with JS regular expressions:

    1. Know whether there is a decimal point in the number, and use different regular expressions depending on that:

      • /(\d)(?=(\d{3})+$)/g for integers
      • /(\d)(?=(\d{3})+\.)/g for decimals
    2. Use two regular expressions, one to match the decimal portion, and a second to do a replace on it.

    function format(num) {
      return num.toString().replace(/^[+-]?\d+/, function(int) {
        return int.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
      });
    }
    
    console.log(format(332432432))
    console.log(format(332432432.3432432))
    console.log(format(-332432432))
    console.log(format(1E6))
    console.log(format(1E-6))

提交回复
热议问题