samjhana joshi
samjhana joshi

Reputation: 2015

can't add two decimal numbers using jQuery

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

Answers (5)

Jignesh Rajput
Jignesh Rajput

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

Starx
Starx

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

tylerl
tylerl

Reputation: 30847

Integer arithmatic rounds down. Use parseFloat instead.

Upvotes: 1

AYK
AYK

Reputation: 3322

Use parseFloat instead of parseInt and check.

Upvotes: 1

user235273
user235273

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

Related Questions