can't add two decimal numbers using jQuery

浪尽此生 提交于 2019-12-20 18:44:10

问题


I am trying to add two decimal values but the returned sum is pure integer. What is wrong? I can't find it. any help will be welcome.

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
});

With the code i am getting only 91 and not 91.96


回答1:


Use parseFloat() instead of 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
});



回答2:


you have to use parseFloat Instead of 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
 });

Check Demo: http://jsfiddle.net/aDYhX/1/




回答3:


Use parseFloat instead of parseInt and check.




回答4:


Integer arithmatic rounds down. Use parseFloat instead.




回答5:


Use parseFloat() instead of parseInt()

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

But, since you want to restrict to two decimal places strictly

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);


来源:https://stackoverflow.com/questions/9987734/cant-add-two-decimal-numbers-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!