代码之家  ›  专栏  ›  技术社区  ›  Elias Zamaria

如何在javascript中以逗号作为千位分隔符打印数字

  •  1347
  • Elias Zamaria  · 技术社区  · 16 年前

    我想打印一个整数 JavaScript 以逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做呢?

    我是这样做的:

    function numberWithCommas(x) {
        x = x.toString();
        var pattern = /(-?\d+)(\d{3})/;
        while (pattern.test(x))
            x = x.replace(pattern, "$1,$2");
        return x;
    }
    

    有更简单或更优雅的方法吗?如果它也能和float一起工作,那就更好了,但这不是必需的。它不需要特定于区域设置来决定句点和逗号。

    43 回复  |  直到 7 年前
        1
  •  2296
  •   Lloyd Banks    8 年前

    我使用了克里的回答,但简化了它,因为我只是为了我的特定目的寻找简单的东西。以下是我所做的:

    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    

    这就是你真正需要知道的。

    @NeilsBom问Regex如何工作。我的解释有点长。它不符合评论,我也不知道把它放在哪里,所以我在这里做。如果有人对把它放在哪里有其他建议,请告诉我。

    regex使用两个lookahead断言:一个正数查找字符串中在其后面一行中有3位数的倍数的任何点,另一个负数断言确保该点只有3位数的倍数。替换表达式在此处放置逗号。

    例如,如果传递“123456789.01”,则肯定断言将匹配7左侧的每个点(因为“789”是3位数的倍数,“678”是3位数的倍数,“567”等)。否定断言检查3位数的倍数后面没有任何位数。“789“后面有一个句点,所以它正好是3位数的倍数,所以这里有一个逗号。”678是3位数的倍数,但后面有一个“9”,所以这3位数是4位数的一组的一部分,逗号不在这组数字后面。类似于“567”。456789“是6位数字,是3的倍数,因此前面加逗号。”345678是3的倍数,但后面有一个“9”,所以没有逗号。等等。“\b”防止regex在字符串的开头加逗号。

    @Neu-rah提到,如果小数点后的数字超过3位,则此函数会在不希望出现的位置添加逗号。如果这是一个问题,您可以使用此函数:

    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return parts.join(".");
    }
    
        2
  •  1277
  •   Avi    8 年前

    我很惊讶没人提到 Number.prototype.toLocaleString . 它是在Javascript1.5中实现的(这是在1999年引入的),所以它基本上支持跨主要浏览器。

    var n = 34523453.345
    n.toLocaleString()
    "34,523,453.345"
    

    从v0.12起,它也在node.js中工作,包括 Intl

    注意这个函数返回的字符串不是数字

    如果你想要不同的东西, Numeral.js 可能很有趣。

        3
  •  197
  •   Joshua Burns    9 年前
    var number = 1234567890; // Example number to be converted
    

    _请注意,javascript具有 maximum integer 价值 9007199254740991


    toLocaleString :

    number.toLocaleString(); // "1,234,567,890"
    
    // A more complex example: 
    var number2 = 1234.56789; // floating point example
    number2.toLocaleString(undefined, {maximumFractionDigits:2}) // "1,234.57"
    


    NumberFormat ( 游猎 不支持):

    var nf = new Intl.NumberFormat();
    nf.format(number); // "1,234,567,890"
    

    根据我所检查的(至少是火狐),它们在性能方面或多或少是相同的。

        4
  •  97
  •   T.J. Crowder    9 年前

    我建议使用phpjs.org number_format()

    function number_format(number, decimals, dec_point, thousands_sep) {
        // http://kevin.vanzonneveld.net
        // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +     bugfix by: Michael White (http://getsprink.com)
        // +     bugfix by: Benjamin Lupton
        // +     bugfix by: Allan Jensen (http://www.winternet.no)
        // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +     bugfix by: Howard Yeend
        // +    revised by: Luke Smith (http://lucassmith.name)
        // +     bugfix by: Diogo Resende
        // +     bugfix by: Rival
        // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
        // +   improved by: davook
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Jay Klehr
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Amir Habibi (http://www.residence-mixte.com/)
        // +     bugfix by: Brett Zamir (http://brett-zamir.me)
        // +   improved by: Theriault
        // +   improved by: Drew Noakes
        // *     example 1: number_format(1234.56);
        // *     returns 1: '1,235'
        // *     example 2: number_format(1234.56, 2, ',', ' ');
        // *     returns 2: '1 234,56'
        // *     example 3: number_format(1234.5678, 2, '.', '');
        // *     returns 3: '1234.57'
        // *     example 4: number_format(67, 2, ',', '.');
        // *     returns 4: '67,00'
        // *     example 5: number_format(1000);
        // *     returns 5: '1,000'
        // *     example 6: number_format(67.311, 2);
        // *     returns 6: '67.31'
        // *     example 7: number_format(1000.55, 1);
        // *     returns 7: '1,000.6'
        // *     example 8: number_format(67000, 5, ',', '.');
        // *     returns 8: '67.000,00000'
        // *     example 9: number_format(0.9, 0);
        // *     returns 9: '1'
        // *    example 10: number_format('1.20', 2);
        // *    returns 10: '1.20'
        // *    example 11: number_format('1.20', 4);
        // *    returns 11: '1.2000'
        // *    example 12: number_format('1.2000', 3);
        // *    returns 12: '1.200'
        var n = !isFinite(+number) ? 0 : +number, 
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            toFixedFix = function (n, prec) {
                // Fix for IE parseFloat(0.55).toFixed(0) = 0;
                var k = Math.pow(10, prec);
                return Math.round(n * k) / k;
            },
            s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
    

    更新02/13/14

    人们一直在报告这不符合预期,所以我做了一个 JS Fiddle 包括自动测试。

    更新日期:2017年11月26日

    下面是一个稍微修改了输出的堆栈片段:

    function number_format(number, decimals, dec_point, thousands_sep) {
        // http://kevin.vanzonneveld.net
        // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +     bugfix by: Michael White (http://getsprink.com)
        // +     bugfix by: Benjamin Lupton
        // +     bugfix by: Allan Jensen (http://www.winternet.no)
        // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
        // +     bugfix by: Howard Yeend
        // +    revised by: Luke Smith (http://lucassmith.name)
        // +     bugfix by: Diogo Resende
        // +     bugfix by: Rival
        // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
        // +   improved by: davook
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Jay Klehr
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Amir Habibi (http://www.residence-mixte.com/)
        // +     bugfix by: Brett Zamir (http://brett-zamir.me)
        // +   improved by: Theriault
        // +   improved by: Drew Noakes
        // *     example 1: number_format(1234.56);
        // *     returns 1: '1,235'
        // *     example 2: number_format(1234.56, 2, ',', ' ');
        // *     returns 2: '1 234,56'
        // *     example 3: number_format(1234.5678, 2, '.', '');
        // *     returns 3: '1234.57'
        // *     example 4: number_format(67, 2, ',', '.');
        // *     returns 4: '67,00'
        // *     example 5: number_format(1000);
        // *     returns 5: '1,000'
        // *     example 6: number_format(67.311, 2);
        // *     returns 6: '67.31'
        // *     example 7: number_format(1000.55, 1);
        // *     returns 7: '1,000.6'
        // *     example 8: number_format(67000, 5, ',', '.');
        // *     returns 8: '67.000,00000'
        // *     example 9: number_format(0.9, 0);
        // *     returns 9: '1'
        // *    example 10: number_format('1.20', 2);
        // *    returns 10: '1.20'
        // *    example 11: number_format('1.20', 4);
        // *    returns 11: '1.2000'
        // *    example 12: number_format('1.2000', 3);
        // *    returns 12: '1.200'
        var n = !isFinite(+number) ? 0 : +number, 
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            toFixedFix = function (n, prec) {
                // Fix for IE parseFloat(0.55).toFixed(0) = 0;
                var k = Math.pow(10, prec);
                return Math.round(n * k) / k;
            },
            s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
        if (s[0].length > 3) {
            s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
        }
        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
    
    var exampleNumber = 1;
    function test(expected, number, decimals, dec_point, thousands_sep)
    {
        var actual = number_format(number, decimals, dec_point, thousands_sep);
        console.log(
            'Test case ' + exampleNumber + ': ' +
            '(decimals: ' + (typeof decimals === 'undefined' ? '(default)' : decimals) +
            ', dec_point: "' + (typeof dec_point === 'undefined' ? '(default)' : dec_point) + '"' +
            ', thousands_sep: "' + (typeof thousands_sep === 'undefined' ? '(default)' : thousands_sep) + '")'
        );
        console.log('  => ' + (actual === expected ? 'Passed' : 'FAILED') + ', got "' + actual + '", expected "' + expected + '".');
        exampleNumber++;
    }
    
    test('1,235',    1234.56);
    test('1 234,56', 1234.56, 2, ',', ' ');
    test('1234.57',  1234.5678, 2, '.', '');
    test('67,00',    67, 2, ',', '.');
    test('1,000',    1000);
    test('67.31',    67.311, 2);
    test('1,000.6',  1000.55, 1);
    test('67.000,00000', 67000, 5, ',', '.');
    test('1',        0.9, 0);
    test('1.20',     '1.20', 2);
    test('1.2000',   '1.20', 4);
    test('1.200',    '1.2000', 3);
    .as-console-wrapper {
      max-height: 100% !important;
    }
        5
  •  66
  •   user1437663    14 年前

    这是@mikez302答案的变体,但经过修改以支持带小数的数字(根据@neu rah的反馈,数字带逗号(12345.6789)->“12345.6789”而不是“12345.6789”

    function numberWithCommas(n) {
        var parts=n.toString().split(".");
        return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
    }
    
        6
  •  57
  •   Tutankhamen    12 年前
    function formatNumber (num) {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
    }
    
    print(formatNumber(2665));      // 2,665
    print(formatNumber(102665));    // 102,665
    print(formatNumber(111102665)); // 111,102,665
    
        7
  •  45
  •   TinhNQ    8 年前

    使用正则表达式

    函数tocommas(value){
    返回值.ToString()。替换(/\b(?=(\d { 3 })+(?)(d))/g,“,”);
    }
    console.log(tocommas(123456789));/123456789
    
    console.log(tocommas(1234567890));/1234567890
    console.log(tocommas(1234));/1234
    < /代码> 
    
    

    使用toLocaleString()

    var number=123456.789;
    
    //请求货币格式
    console.log(number.toLocaleString('de-de',style:'currency',currency:'eur'));
    //123.456,79_
    
    //日元不使用次要单位
    console.log(number.toLocaleString('ja-jp',style:'currency',currency:'jpy')))
    //123457
    
    //限制为三位有效数字
    console.log(number.toLocaleString(‘en-in’,maximumSignificantDigits:3));
    //1,23000
    < /代码> 
    
    

    refmdn:number.prototype.toLocaleString()。

    使用intl.numberFormat()。

    var number=123456.789;
    
    console.log(new intl.number format('de-de',style:'currency',currency:'eur').format(number));
    //预期产量:“123.456,79_”
    
    //日元不使用次要单位
    console.log(new intl.number format('ja-jp',style:'currency',currency:'jpy').format(number));
    //预期输出:“123457”
    
    //限制为三位有效数字
    console.log(new intl.number format('en-in',maximumSignificantDigits:3).format(number));
    
    //预期输出:“1,23000”
    < /代码> 
    
    

    refintl.numberformat

    在这里演示

    <script type=“text/javascript”>
    //使用正则表达式
    函数tocommas(value){
    返回值.ToString()。替换(/\b(?=(\d { 3 })+(?)(d))/g,“,”);
    }
    
    函数逗号()。{
    var num1=document.myform.number1.value;
    
    //使用正则表达式
    document.getElementByID('result1').value=tocommas(parseInt(num1));
    //使用toLocaleString()。
    
    document.getElementByID('result2').value=parseInt(num1).toLocaleString('ja-jp','{
    style:'货币',
    货币:“日元”
    (});
    
    //使用intl.numberFormat()。
    document.getElementByID('result3').value=new intl.numberFormat('ja-jp','{
    style:'货币',
    货币:“日元”
    })格式(num1);
    }
    & /脚本& GT;
    <form name=“myform”>
    <input type=“text”name=“number1”value=“123456789”>
    & BR>
    <input type=“button”name=“button”value=“=>”onclick=“commas()”>
    <br>使用正则表达式
    & BR>
    <input type=“text”id=“result1”name=“result1”value=“>
    <br>使用toLocaleString()。
    & BR>
    <input type=“text”id=“result2”name=“result2”value=“>
    <br>使用intl.numberFormat()。
    & BR>
    <input type=“text”id=“result3”name=“result3”value=“>
    
    </Form>

    性能

    http://jsben.ch/sifrd

    使用ToLocaleString()。

    var number = 123456.789;
    
    // request a currency format
    console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
    // → 123.456,79 €
    
    // the Japanese yen doesn't use a minor unit
    console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
    // → ¥123,457
    
    // limit to three significant digits
    console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
    // → 1,23,000
    

    裁判MDN:Number.prototype.toLocaleString()

    使用intl.numberFormat()。

    var number = 123456.789;
    
    console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
    // expected output: "123.456,79 €"
    
    // the Japanese yen doesn't use a minor unit
    console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
    // expected output: "ï¿¥123,457"
    
    // limit to three significant digits
    console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
    
    // expected output: "1,23,000"
    

    裁判Intl.NumberFormat

    在这里演示

    <script type="text/javascript">
      // Using Regular expression
      function toCommas(value) {
        return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      }
    
      function commas() {
        var num1 = document.myform.number1.value;
    
        // Using Regular expression
        document.getElementById('result1').value = toCommas(parseInt(num1));
        // Using toLocaleString()
    
        document.getElementById('result2').value = parseInt(num1).toLocaleString('ja-JP', {
          style: 'currency',
          currency: 'JPY'
        });
    
        // Using Intl.NumberFormat()
        document.getElementById('result3').value = new Intl.NumberFormat('ja-JP', {
          style: 'currency',
          currency: 'JPY'
        }).format(num1);
      }
    </script>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE="123456789">
      <br>
      <INPUT TYPE="button" NAME="button" Value="=>" onClick="commas()">
      <br>Using Regular expression
      <br>
      <INPUT TYPE="text" ID="result1" NAME="result1" VALUE="">
      <br>Using toLocaleString()
      <br>
      <INPUT TYPE="text" ID="result2" NAME="result2" VALUE="">
      <br>Using Intl.NumberFormat()
      <br>
      <INPUT TYPE="text" ID="result3" NAME="result3" VALUE="">
    
    </FORM>

    性能

    Performance http://jsben.ch/sifRd

        8
  •  33
  •   Dustin Sun Bala cse    9 年前

    Intl.NumberFormat

    本地JS函数。支持IE11、EDGE、最新Safari、Chrome、Firefox、Opera、iOS版Safari和Android版Chrome。

    var number = 3500;
    
    console.log(new Intl.NumberFormat().format(number));
    // → '3,500' if in US English locale
    
        9
  •  31
  •   None    12 年前

    感谢大家的回复。我建立了一些答案来制定一个更“一刀切”的解决方案。

    第一个片段添加了一个模仿 PHP 的 number_format() 到数字原型。如果我正在格式化一个数字,我通常需要小数位,所以函数需要显示小数位的数目。有些国家使用逗号作为小数,使用小数作为千位分隔符,因此函数允许设置这些分隔符。

    Number.prototype.numberFormat = function(decimals, dec_point, thousands_sep) {
        dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
        thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';
    
        var parts = this.toFixed(decimals).split('.');
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_sep);
    
        return parts.join(dec_point);
    }
    

    您可以如下使用:

    var foo = 5000;
    console.log(foo.numberFormat(2)); // us format: 5,000.00
    console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00
    

    我发现我经常需要为数学运算返回数字,但parsefloat将5000转换为5,只需取第一个整数值序列。所以我创建了自己的float转换函数并将其添加到字符串原型中。

    String.prototype.getFloat = function(dec_point, thousands_sep) {
        dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
        thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';
    
        var parts = this.split(dec_point);
        var re = new RegExp("[" + thousands_sep + "]");
        parts[0] = parts[0].replace(re, '');
    
        return parseFloat(parts.join(dec_point));
    }
    

    现在您可以使用以下两种功能:

    var foo = 5000;
    var fooString = foo.numberFormat(2); // The string 5,000.00
    var fooFloat = fooString.getFloat(); // The number 5000;
    
    console.log((fooString.getFloat() + 1).numberFormat(2)); // The string 5,001.00
    
        10
  •  21
  •   bummi Haisum Usman    11 年前

    我认为这是最短的正则表达式:

    /\B(?=(\d{3})+\b)/g
    
    "123456".replace(/\B(?=(\d{3})+\b)/g, ",")
    

    我在一些数字上查了一下,结果成功了。

        11
  •  18
  •   Sinan    9 年前

    Number.prototype.toLocaleString() 如果它是由所有浏览器本地提供的,那就太棒了。 (狩猎) .

    我查了所有其他的答案,但似乎没有人多填。这是一个POC,实际上是前两个答案的组合;如果 toLocaleString 它使用它,如果不使用,它使用自定义函数。

    var putThousandsSeparators;
    
    putThousandsSeparators = function(value, sep) {
      if (sep == null) {
        sep = ',';
      }
      // check if it needs formatting
      if (value.toString() === value.toLocaleString()) {
        // split decimals
        var parts = value.toString().split('.')
        // format whole numbers
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, sep);
        // put them back together
        value = parts[1] ? parts.join('.') : parts[0];
      } else {
        value = value.toLocaleString();
      }
      return value;
    };
    
    alert(putThousandsSeparators(1234567.890));
        12
  •  15
  •   phette23    12 年前

    千位分隔符可以使用浏览器的 Intl 对象:

    Intl.NumberFormat().format(1234);
    // returns "1,234" if the user's locale is en_US, for example
    

    见 MDN's article on NumberFormat 对于更多,您可以指定区域设置行为或用户的默认值。这是一个更简单的方法,因为它尊重本地差异;许多国家使用句点分隔数字,而逗号表示小数。

    Intl.NumberFormat还没有在所有浏览器中都可用,但它可以在最新的Chrome、Opera等浏览器中使用。火狐的下一个版本应该支持它。WebKit似乎没有实现的时间表。

        13
  •  13
  •   mariobgr    8 年前

    您可以使用此过程设置所需货币的格式。

    var nf = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    });
    nf.format(123456.789); // ‘$123,456.79’
    

    有关详细信息,您可以访问此链接。

    https://www.justinmccandless.com/post/formatting-currency-in-javascript/

        14
  •  12
  •   Shital Shah    12 年前

    如果您处理的是货币值和格式设置,那么可能需要添加微小的 accounting.js 它可以处理很多边缘案例和本地化:

    // Default usage:
    accounting.formatMoney(12345678); // $12,345,678.00
    
    // European formatting (custom symbol and separators), could also use options object as second param:
    accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
    
    // Negative values are formatted nicely, too:
    accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
    
    // Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
    accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP
    
        15
  •  11
  •   fregante    11 年前

    下面的代码使用char扫描,因此没有regex。

    function commafy( num){
      var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
      while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                      +s.charAt(i) +o }
      return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
    }
    

    表现出良好的性能: http://jsperf.com/number-formatting-with-commas/5

    2015.4.26:在num<0时解决问题的小修复。见 https://jsfiddle.net/runsun/p5tqqvs3/

        16
  •  8
  •   aleclarson    8 年前

    下面是一个简单的函数,它为千位分隔符插入逗号。它使用数组函数而不是regex。

    /**
     * Format a number as a string with commas separating the thousands.
     * @param num - The number to be formatted (e.g. 10000)
     * @return A string representing the formatted number (e.g. "10,000")
     */
    var formatNumber = function(num) {
        var array = num.toString().split('');
        var index = -3;
        while (array.length + index > 0) {
            array.splice(index, 0, ',');
            // Decrement by 4 since we just added another unit to the array.
            index -= 4;
        }
        return array.join('');
    };
    

    代码沙盒链接示例: https://codesandbox.io/s/p38k63w0vq

        17
  •  7
  •   Ronnie Overby    12 年前

    我写这篇文章之前,在这篇文章上跌跌撞撞。没有regex,您实际上可以理解代码。

    $(function(){
      
      function insertCommas(s) {
    
        // get stuff before the dot
        var d = s.indexOf('.');
        var s2 = d === -1 ? s : s.slice(0, d);
    
        // insert commas every 3 digits from the right
        for (var i = s2.length - 3; i > 0; i -= 3)
          s2 = s2.slice(0, i) + ',' + s2.slice(i);
    
        // append fractional part
        if (d !== -1)
          s2 += s.slice(d);
    
        return s2;
    
      }
      
      
      $('#theDudeAbides').text( insertCommas('1234567.89012' ) );
      
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div id="theDudeAbides"></div>
        18
  •  6
  •   Carlos A. Ortiz    10 年前

    对我来说,最好的答案是像一些会员所说的那样使用摇头丸。 如果要包含“$”符号,只需添加languaje和type选项。 下面是将数字格式化为墨西哥比索的示例

    var n = 1234567.22
    alert(n.toLocaleString("es-MX",{style:"currency", currency:"MXN"}))

    捷径

    1234567.22.toLocaleString("es-MX",{style:"currency", currency:"MXN"})
    
        19
  •  5
  •   Community Mohan Dere    9 年前

    让我努力提高 uKolka 的 answer 或许可以帮助别人节省一些时间。

    使用 Numeral.js .

    document.body.textContent = numeral(1234567).format('0,0');
    <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>

    你应该一起去 Number.prototype.toLocaleString() 只有其 browser compatibilty 不是问题。

        20
  •  5
  •   Kiry Meas    7 年前
    var formatNumber = function (number) {
      var splitNum;
      number = Math.abs(number);
      number = number.toFixed(2);
      splitNum = number.split('.');
      splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return splitNum.join(".");
    }
    

    编辑: 该函数只能使用正数。对于Expple:

    var number = -123123231232;
    formatNumber(number)
    

    输出:“123123231232”

    但要回答上面的问题 toLocaleString() 方法只是解决了问题。

    var number = 123123231232;
        number.toLocaleString()
    

    输出:“123123231232”

    加油!

        21
  •  3
  •   ROMANIA_engineer Alexey    12 年前

    我认为这个函数将处理与这个问题相关的所有问题。

    function commaFormat(inputString) {
        inputString = inputString.toString();
        var decimalPart = "";
        if (inputString.indexOf('.') != -1) {
            //alert("decimal number");
            inputString = inputString.split(".");
            decimalPart = "." + inputString[1];
            inputString = inputString[0];
            //alert(inputString);
            //alert(decimalPart);
    
        }
        var outputString = "";
        var count = 0;
        for (var i = inputString.length - 1; i >= 0 && inputString.charAt(i) != '-'; i--) {
            //alert("inside for" + inputString.charAt(i) + "and count=" + count + " and outputString=" + outputString);
            if (count == 3) {
                outputString += ",";
                count = 0;
            }
            outputString += inputString.charAt(i);
            count++;
        }
        if (inputString.charAt(0) == '-') {
            outputString += "-";
        }
        //alert(outputString);
        //alert(outputString.split("").reverse().join(""));
        return outputString.split("").reverse().join("") + decimalPart;
    }
    
        22
  •  2
  •   Wayne    12 年前

    已经有很多好的答案了。这是另一个,只是为了好玩:

    function format(num, fix) {
        var p = num.toFixed(fix).split(".");
        return p[0].split("").reduceRight(function(acc, num, i, orig) {
            if ("-" === num && 0 === i) {
                return num + acc;
            }
            var pos = orig.length - i - 1
            return  num + (pos && !(pos % 3) ? "," : "") + acc;
        }, "") + (p[1] ? "." + p[1] : "");
    }
    

    一些例子:

    format(77.03453, 2); // "77.03"
    format(78436589374); // "78,436,589,374"
    format(784, 4);      // "784.0000"
    format(-123456);     // "-123,456"
    
        23
  •  1
  •   bartburkhardt    14 年前

    我把tofixed添加到 AKI143S 的解决方案。 此解决方案使用点作为千位分隔符,使用逗号作为精度。

    function formatNumber( num, fixed ) { 
        var decimalPart;
    
        var array = Math.floor(num).toString().split('');
        var index = -3; 
        while ( array.length + index > 0 ) { 
            array.splice( index, 0, '.' );              
            index -= 4;
        }
    
        if(fixed > 0){
            decimalPart = num.toFixed(fixed).split(".")[1];
            return array.join('') + "," + decimalPart; 
        }
        return array.join(''); 
    };
    

    实例;

    formatNumber(17347, 0)  = 17.347
    formatNumber(17347, 3)  = 17.347,000
    formatNumber(1234563.4545, 3)  = 1.234.563,454
    
        24
  •  1
  •   Paulo Buchsbaum    13 年前

    @user1437663的解决方案非常好。

    真正理解解决方案的人正在准备理解复杂的正则表达式。

    一个小的改进使它更易读:

    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        return parts[0].replace(/\B(?=(\d{3})+(?=$))/g, ",") + (parts[1] ? "." + parts[1] : "");
    }
    

    模式从 \b 避免在单词开头使用逗号。有趣的是,模式返回为空,因为 \b 不前进“光标”(同样适用于 $ )

    o \b 后面是一个不太知名的资源,但它是Perl正则表达式的一个强大功能。

                Pattern1 (? = (Pattern2) ).
    

    神奇的是括号里的内容( 图案化2 )是遵循上一个模式的模式( 图案化 )但不前进光标,也不是返回模式的一部分。这是一种未来的模式。当有人向前看,但实际上不走路时,这是相似的!

    在这种情况下 图案化2 是

    \d{3})+(?=$)
    

    它表示3位数字(一次或多次),后跟字符串结尾($)

    最后, 替换 方法将找到的模式(空字符串)的所有匹配项更改为逗号。只有在剩余部分是3位数的倍数的情况下才会发生这种情况。 (例如,未来光标到达原点的末端)。

        25
  •  1
  •   Rob W jminkler    13 年前

    我认为你的解决方案是我见过的较短的方案之一。我不认为有任何标准的javascript函数可以完成这类工作,所以您可能是自己完成的。

    我检查了CSS3规范,看看是否有可能在CSS中实现这一点,但是除非您希望每个数字都有自己的格式。 <span> 我认为这是不可能的。

    我确实在上找到了一个项目 Google Code 看起来很有希望: flexible-js-formatting . 我没有用过,但它看起来很灵活,有单元测试使用 JsUnit . 开发人员也有很多关于这个主题的文章(尽管很旧)。

    一定要考虑国际用户:许多国家使用空格作为分隔符,并使用逗号将小数与数字的整数部分分隔开。

        26
  •  1
  •   Eluny    11 年前

    我已经调整了您的代码以在文本框(input type=“text”)中工作,因此我们可以实时输入和删除数字,而不会丢失光标。如果您在删除时选择范围,它也可以工作。您可以自由使用箭头和Home/End按钮。
    谢谢你帮我节省时间!

    //function controls number format as "1,532,162.3264321"
    function numberWithCommas(x) {
        var e = e || window.event;
        if (e.keyCode >= '35' && e.keyCode <= '40') return; //skip arrow-keys
        var selStart = x.selectionStart, selEnd = x.selectionEnd; //save cursor positions
        var parts = x.value.toString().split(".");
        var part0len = parts[0].length; //old length to check if new ',' would be added. Need for correcting new cursor position (+1 to right).
    
        //if user deleted ',' - remove previous number instead (without selection)
        if (x.selectionLength == 0 && (e.keyCode == 8 || e.keyCode == 46)) {//if pressed 8-backspace or 46-delete button
            var delPos = parts[0].search(/\d{4}/);
            if (delPos != -1) {//if found 4 digits in a row (',' is deleted)
                if (e.keyCode == 8) {//if backspace flag
                    parts[0] = parts[0].slice(0, selStart - 1) + parts[0].slice(selEnd, parts[0].length);
                    selEnd--;
                    if (selStart > selEnd) selStart = selEnd;
                } else {
                    parts[0] = parts[0].slice(0, selStart) + parts[0].slice(selEnd + 1, parts[0].length);
                    selStart++;
                    if (selEnd < selStart) selEnd = selStart;
                }
            }
        }
    
       var hasMinus = parts[0][0] == '-';
       parts[0] = (hasMinus ? '-' : '') + parts[0].replace(/[^\d]*/g, ""); //I'd like to clear old ',' to avoid things like 1,2,3,5,634.443216
       parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); //sets ',' between each 3 digits
       if (part0len < parts[0].length) { //move cursor to right if added new ','
           selStart++;
           selEnd++;
       } else if (part0len > parts[0].length) { //..or if removed last one ','
           selStart--;
           selEnd--;
       }
       x.value = parts.join(".");
       x.setSelectionRange(selStart, selEnd); //restoring cursor position
    }
    function saveSelectionLength(x) {
        x.selectionLength = x.selectionEnd - x.selectionStart;
    }
    

    要使用它,只需添加两个事件-onkeyup和onkeydown

    <asp:TextBox runat="server" ID="val" Width="180px" onKeyUp="numberWithCommas(this);" onKeyDown="saveSelectionLength(this);"/>
    
        27
  •  1
  •   Ethan Chen    9 年前

    如果您碰巧使用AngularJS,这里有一个货币过滤器可以帮助您: http://www.w3schools.com/angular/ng_filter_currency.asp

        28
  •  1
  •   Matt Scheurich    9 年前

    这是我的尝试:

    编辑:以小数形式添加

    function splitMille(n, separator = ',') {
      // Cast to string
      let num = (n + '')
    
      // Test for and get any decimals (the later operations won't support them)
      let decimals = ''
      if (/\./.test(num)) {
        // This regex grabs the decimal point as well as the decimal numbers
        decimals = num.replace(/^.*(\..*)$/, '$1')
      }
      
      // Remove decimals from the number string
      num = num.replace(decimals, '')
        // Reverse the number string through Array functions
        .split('').reverse().join('')
        // Split into groups of 1-3 characters (with optional supported character "-" for negative numbers)
        .match(/[0-9]{1,3}-?/g)
        // Add in the mille separator character and reverse back
        .join(separator).split('').reverse().join('')
    
      // Put the decimals back and output the formatted number
      return `${num}${decimals}`
    }
    
    let testA = splitMille(1234)
    let testB = splitMille(-1234)
    let testC = splitMille(123456.789)
    let testD = splitMille(9007199254740991)
    let testE = splitMille(1000.0001)
    
    console.log('Results!\n\tA: %s\n\tB: %s\n\tC: %s\n\tD: %s\n\tE: %s', testA, testB, testC, testD, testE)
        29
  •  1
  •   arosolino    9 年前

    这里有一个支持int&decimal的单行函数。我还留了一些代码将数字转换为字符串。

        function numberWithCommas(x) {
            return (x=x+'').replace(new RegExp('\\B(?=(\\d{3})+'+(~x.indexOf('.')?'\\.':'$')+')','g'),',');
        }
    
        30
  •  1
  •   Sverrisson    8 年前

    在这里没有找到一个现代和全面的解决方案之后,我编写了一个箭头函数(不带regex)来解决格式化问题,它允许调用者提供 分数位数 以及 期间和千位分隔符 对于欧洲和世界其他地区。

    实例:

    numberFormatter(1234567890.123456) => 1,234,567,890
    numberFormatter(1234567890.123456, 4) => 1,234,567,890.1235
    numberFormatter(1234567890.123456, 4, '.', ',') => 1.234.567.890,1235 Europe
    

    这是写的函数 ES6 (现代语法):

    const numberFormatter = (number, fractionDigits = 0, thousandSeperator = ',', fractionSeperator = '.') => {
        if (number!==0 && !number || !Number.isFinite(number)) return number
        const frDigits = Number.isFinite(fractionDigits)? Math.min(Math.max(fractionDigits, 0), 7) : 0
        const num = number.toFixed(frDigits).toString()
    
        const parts = num.split('.')
        let digits = parts[0].split('').reverse()
        let sign = ''
        if (num < 0) {sign = digits.pop()}
        let final = []
        let pos = 0
    
        while (digits.length > 1) {
            final.push(digits.shift())
            pos++
            if (pos % 3 === 0) {final.push(thousandSeperator)}
        }
        final.push(digits.shift())
        return `${sign}${final.reverse().join('')}${frDigits > 0 ? fractionSeperator : ''}${frDigits > 0 && parts[1] ? parts[1] : ''}`
    }
    

    它已经被 测试阴性、不良输入和NAN情况 . 如果输入是 南 然后它简单地返回它。