can't add two decimal numbers using jQuery

前提是你 提交于 2019-12-03 06:06:52

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

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/

Use parseFloat instead of parseInt and check.

Integer arithmatic rounds down. Use parseFloat instead.

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