Добавляйте запятую к числам через каждые три цифры

StackOverflow https://stackoverflow.com/questions/1990512

  •  22-09-2019
  •  | 
  •  

Вопрос

Как я могу форматировать числа, используя разделитель через запятую через каждые три цифры с помощью jQuery?

Например:

╔═══════════╦═════════════╗
║   Input   ║   Output    ║
╠═══════════╬═════════════╣
║       298 ║         298 ║
║      2984 ║       2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝
Это было полезно?

Решение

У @Paul Creasey было самое простое решение в виде регулярного выражения, но здесь оно представлено в виде простого плагина jQuery:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

Затем вы могли бы использовать его следующим образом:

$("span.numbers").digits();

Другие советы

Вы могли бы использовать Number.toLocaleString():

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534

Что-то вроде этого, если вы используете регулярное выражение, но не уверены в точном синтаксисе для замены, то!

MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

Вы могли бы попробовать Числовой форматировщик.

$(this).format({format:"#,###.00", locale:"us"});

Он также поддерживает различные локали, включая, конечно, США.

Вот очень упрощенный пример того, как это использовать:

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="jquery.numberformatter.js"></script>
        <script>
        $(document).ready(function() {
            $(".numbers").each(function() {
                $(this).format({format:"#,###", locale:"us"});
            });
        });
        </script>
    </head>
    <body>
        <div class="numbers">1000</div>
        <div class="numbers">2000000</div>
    </body>
</html>

Выходной сигнал:

1,000
2,000,000

Это не jQuery, но у меня это работает.Взято из этот сайт.

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Ответ 2016 года:

Javascript имеет эту функцию, поэтому нет необходимости в Jquery.

yournumber.toLocaleString("en");

Используйте номер функции();

$(function() {

  var price1 = 1000;
  var price2 = 500000;
  var price3 = 15245000;

  $("span#s1").html(Number(price1).toLocaleString('en'));
  $("span#s2").html(Number(price2).toLocaleString('en'));
  $("span#s3").html(Number(price3).toLocaleString('en'));

  console.log(Number(price).toLocaleString('en'));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<span id="s1"></span><br />
<span id="s2"></span><br />
<span id="s3"></span><br />

Более тщательное решение

Ядром этого является replace звони.Пока что я не думаю, что какое-либо из предложенных решений обрабатывает все следующие случаи:

  • Целые числа: 1000 => '1,000'
  • Струны: '1000' => '1,000'
  • Для строк:
    • Сохраняет нули после десятичной дроби: 10000.00 => '10,000.00'
    • Отбрасывает начальные нули перед десятичной дробью: '01000.00 => '1,000.00'
    • Не добавляет запятые после десятичной дроби: '1000.00000' => '1,000.00000'
    • Консервы , ведущие - или +: '-1000.0000' => '-1,000.000'
    • Возвращает неизмененные строки, содержащие не цифры: '1000k' => '1000k'

Следующая функция выполняет все вышеперечисленное.

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

Вы могли бы использовать это в плагине jQuery, подобном этому:

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};

Вы также можете посмотреть на jquery Форматируемая валюта плагин (автором которого я являюсь);он также поддерживает несколько локализаций, но может иметь накладные расходы на поддержку валюты, которая вам не нужна.

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });

Вот мой javascript, протестированный только в Firefox и Chrome

<html>
<header>
<script>
    function addCommas(str){
        return str.replace(/^0+/, '').replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function test(){
        var val = document.getElementById('test').value;
        document.getElementById('test').value = addCommas(val);
    }
</script>
</header>
<body>
<input id="test" onkeyup="test();">
</body>
</html>

Очень простой способ заключается в использовании toLocaleString() функция

tot = Rs.1402598 //Result : Rs.1402598

tot.toLocaleString() //Result : Rs.1,402,598
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top