为什么总和总是返回一个错误的值

Why keeps sum returning a false value

本文关键字:一个 错误 返回 为什么      更新时间:2023-09-26

我在这样的表单中有一些输入值:

<tr>
  <td>
      <input type="text" disabled class="qty" value="1" name="quantity">
  </td>
  <td>
    <span class="euro">€</span><input type="text" disabled class="price" value="0,60">
  </td>
</tr>
<tr>
  <td>
      <input type="text" disabled class="qty" value="1" name="quantity">
  </td>
  <td>
    <span class="euro">€</span><input type="text" disabled class="price" value="0,25">
  </td>
</tr>
// below table row is empty because product is not on stock! //
<tr>
  <td></td>
  <td></td>
</tr>
//etc...

我尝试对qtyprice的输入值求和,但我的脚本一直返回NaN作为结果。我认为这是因为当产品没有库存时,表格单元格是空的。因此返回CCD_ 4或CCD_。我读过很多这样的帖子,但这并不能解决我的问题。

我有这个:

function update_amounts(){
  var sum = 0.0;
  $('#inspiration .table tbody tr').each(function() {
    var qty = $(this).find('.qty').val();
    var price = $(this).find('.price').val();
    console.log(price, qty);
    var amount = (qty*price)
        sum+=amount;
  });
  $('.total').text(sum);    
}

我已经尝试过的是:

var qty = parseInt($(this).find('.qty').val()) || 0;
var price = parseFloat($(this).find('.price').val()) || 0;

和:

var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
qty= parseInt(qty) || 0;
price= parseFloat(price) || 0;
console.log returns
    (2) 1 0
        0 0
    (3) 1 0

以下是console.log返回的原始代码(第一个是价格,第二个是数量):

0,60 1
0,90 1
undefined undefined
0,14 1
0,12 1
0,75 1

我不知道有什么新的选择来解决这个问题!

您需要使用.字符来启动浮点,而不是,

value="0,60"将不会被视为一个数字。value="0.60"将是.

%  node
> "0.60" * 5
3
> "0,60" * 5
NaN
>

当运行parseFloat时,它将到达,,并停止将其余部分视为数字,因此您最终得到0

> parseFloat("0.60") * 5
3
> parseFloat("0,60") * 5
0