如何在javascript中使用小数

How can I work with decimals in javascript?

本文关键字:小数 javascript      更新时间:2023-11-09

在过去的一个小时里,我尝试了几种不同的解决方案,但都没有解决我的问题。

我有各种输入字段,其中包含十进制数(产品价格),例如98.00

循环浏览项目列表,我需要将字段添加在一起:

  // Calculate sub-total
  $('.selected_list li.order_line:visible').each(function(){
    var item_cost = $(this).find('input.item_cost').val();
    sub_total = sub_total + item_cost;
  })

如何添加这些项并得到包含两个小数的结果
我的小提琴在这里:http://jsfiddle.net/EgGUm/

使用parseFloat:

 var item_cost = parseFloat($(this).find('input.item_cost').val());

更多信息,请点击此处

您可以使用parseFloat()来转换字符串。我已经更新了你的Fiddle:http://jsfiddle.net/EgGUm/11/

  // Calculate sub-total
  $('.selected_list li.order_line:visible').each(function(){
    var item_cost = parseFloat($(this).find('input.item_cost').val());
    sub_total = sub_total + item_cost;
  })