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

问题描述 投票:0回答:1

在此解决方案中找到了此解决方

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

在这个链接add commas to a number in jQuery

我想在我的项目中应用它。它在一列中工作,但在价格和子总数中不起作用

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
    }
    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>

非常感谢你提前!

javascript jquery numbers comma
1个回答
1
投票

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

似乎对于某些值,函数commaSeparateNumber不能按预期工作。我将其从下面的片段中删除,并将其替换为toLocaleString(),其中包含语言环境参数和最小/最大分数.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>
© www.soinside.com 2019 - 2024. All rights reserved.