无法使用jQuery添加两个十进制数

15

我试图将两个十进制值相加,但返回的和是整数。出了什么问题?我找不到原因。任何帮助都将受到欢迎。

jQuery(".delivery-method #ship_select").change(function(){
    var cost = jQuery(this).val(); 
    jQuery("#delivery_cost").val(cost); //returns 20.00
    var tot = parseInt(cost) + parseInt(total); //total returns 71.96
});

我的代码只能得到 91 而不能得到 91.96


parseInt()会使你的逗号值失效。 - Neysor
5个回答

34
使用 parseFloat() 代替 parseInt()
jQuery(".delivery-method #ship_select").change(function(){
    var cost = jQuery(this).val(); 
    jQuery("#delivery_cost").val(cost); //returns 20.00
    var tot = parseFloat(cost) + parseFloat(total); //total returns 71.96
});

7

在使用时,您需要使用parseFloat而不是parseInt

jQuery(".delivery-method #ship_select").change(function(){
      var cost = jQuery(this).val(); 
      jQuery("#delivery_cost").val(cost); //returns 20.00
     var tot = parseFloat(cost) + parseFloat(total); //total returns 71.96
 });

示例演示: http://jsfiddle.net/aDYhX/1/


2

使用parseFloat()代替parseInt()

var tot = parseFloat(cost) + parseFloat(total);

但是,由于您希望严格限制为两位小数

function roundNumber(num, dec) {
   var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
   return result;
}

var tot = roundNumber((cost+total), 2);

1

使用parseFloat而不是parseInt并进行检查。


1

整数运算会向下取整。请使用parseFloat


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接