问题
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