Regular Expression for formatting numbers in JavaScript

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

    Formatting a number can be handled elegantly with one line of code.

    This code extends the Number object; usage examples are included below.

    Code:

    Number.prototype.format = function () {
        return this.toString().split( /(?=(?:\d{3})+(?:\.|$))/g ).join( "," );
    };
    

    How it works

    The regular expression uses a look-ahead to find positions within the string where the only thing to the right of it is one or more groupings of three numbers, until either a decimal or the end of string is encountered. The .split() is used to break the string at those points into array elements, and then the .join() merges those elements back into a string, separated by commas.

    The concept of finding positions within the string, rather than matching actual characters, is important in order to split the string without removing any characters.

    Usage examples:

    var n = 9817236578964235;
    alert( n.format() );    // Displays "9,817,236,578,964,235"
    
    n = 87345.87;
    alert( n.format() );    // Displays "87,345.87"
    

    Of course, the code can easily be extended or changed to handle locale considerations. For example, here is a new version of the code that automatically detects the locale settings and swaps the use of commas and periods.

    Locale-aware version:

    Number.prototype.format = function () {
    
        if ((1.1).toLocaleString().indexOf(".") >= 0) {
            return this.toString().split( /(?=(?:\d{3})+(?:\.|$))/g ).join( "," );
        }
        else {
            return this.toString().split( /(?=(?:\d{3})+(?:,|$))/g ).join( "." );
        }
    };
    

    Unless it's really necessary, I prefer the simplicity of the first version though.

提交回复
热议问题