Reputation: 2015
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
Upvotes: 15
Views: 37077
Reputation: 3558
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/
Upvotes: 7
Reputation: 78971
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);
Upvotes: 2
Reputation:
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
});
Upvotes: 34