向 jquery 中的 123,456.78 这样的数字添加逗号的最佳方法

best approach in adding a comma to a number like 123,456.78 in jquery

在这个解决方案中找到了这个解决方案

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, ''+','+'');
    }
    return val;
  } 

在这个linkadd commas to a number in jQuery

我正在尝试将它应用到我的项目中。它在一栏中有效,但在 pricesub total

中无效

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, ''+','+'');
    }
    return val;
  } 
  

var rowCount = 1;
  
  $('#add').click(function() {
    rowCount++;
    $('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]"  for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});

// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
  getTotalCost($(this).attr("for"));
});

$(document).on('click', '.btn_remove', function() {
  var button_id = $(this).attr('id');
  $('#row'+button_id+'').remove();
});

// Using a new index rather than your global variable i
function getTotalCost(ind) {
  var qty = $('#quantity_'+ind).val();
  var price = $('#product_price_'+ind).val();
  var totNumber = (qty * price);
  var tot = totNumber.toFixed(2);
  tot = commaSeparateNumber(totNumber);
  $('#total_cost_'+ind).val(tot);
  calculateSubTotal();
}

function calculateSubTotal() {
  var subtotal = 0;
  $('.total_cost').each(function() {
     subtotal += parseFloat($(this).val());
  });
  $('#subtotal').val(commaSeparateNumber(subtotal));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
        <div class="col-md-12">
          <div class="line line-dashed line-lg pull-in"></div>
          <div class="row">
            <table class="table table-bordered" id="orders">
              <tr>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total Cost</th>
                <th>
                </th>
              </tr>
              <tr>
                <td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
                <td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
                <td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
                <td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
              </tr>
            </table>
            <input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>            
          </div>
        </div>

        <div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
        
        <div class="col-md-12 nopadding">
          <div class="col-md-4 col-md-offset-4 pull-right nopadding">
            <div class="col-md-8 pull-right nopadding">
              <div class="form-group">
                <td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
              </div>
            </div>
            <div class="col-md-3 pull-right">
              <div class="form-group">
                <label>Subtotal</label>
              </div>
            </div>
          </div>
        </div>
</body>
</html>

在此先感谢您!

问题是 parseFloat 无法正确解析总成本文本框中的值,因为它包含一个或多个 ,。在解析为浮动之前,您需要从字符串中删除 , 。您可以通过在 calculateSubTotal 函数中对文本框值调用 .replace(/,/g,'') 来删除任何 ,

对于某些值,函数 commaSeparateNumber 似乎没有按预期工作。我从下面的代码片段中删除了它,并将其替换为 toLocaleString(),它采用区域设置参数和 minimum/maximum 小数位 .toLocalString("en-US", { maximumFractionDigits: 2})。将语言环境设置为您知道使用 , 分隔千位的语言环境。如果您知道这不会成为问题,您可以为语言环境传递 undefined

您的代码段已更新如下:

var rowCount = 1;
  
  $('#add').click(function() {
    rowCount++;
    $('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]"  for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});

// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
  getTotalCost($(this).attr("for"));
});

$(document).on('click', '.btn_remove', function() {
  var button_id = $(this).attr('id');
  $('#row'+button_id+'').remove();
});

// Using a new index rather than your global variable i
function getTotalCost(ind) {
  var qty = $('#quantity_'+ind).val();
  var price = $('#product_price_'+ind).val();
  var totNumber = (qty * price);
  // .toLocaleString
  var tot = totNumber.toLocaleString("en-US", { maximumFractionDigits: 2});
  $('#total_cost_'+ind).val(tot);
  calculateSubTotal();
}

function calculateSubTotal() {
  var subtotal = 0;
  $('.total_cost').each(function() {
                                       // replace ',' here
     subtotal += parseFloat($(this).val().replace(/,/g,''));
  });
  // toLocaleString
  $('#subtotal').val(subtotal.toLocaleString("en-US", { maximumFractionDigits: 2}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
        <div class="col-md-12">
          <div class="line line-dashed line-lg pull-in"></div>
          <div class="row">
            <table class="table table-bordered" id="orders">
              <tr>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total Cost</th>
                <th>
                </th>
              </tr>
              <tr>
                <td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
                <td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
                <td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
                <td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
              </tr>
            </table>
            <input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>            
          </div>
        </div>

        <div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
        
        <div class="col-md-12 nopadding">
          <div class="col-md-4 col-md-offset-4 pull-right nopadding">
            <div class="col-md-8 pull-right nopadding">
              <div class="form-group">
                <td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
              </div>
            </div>
            <div class="col-md-3 pull-right">
              <div class="form-group">
                <label>Subtotal</label>
              </div>
            </div>
          </div>
        </div>
</body>
</html>