April 3, 2012

can't add two decimal numbers using jQuery

Question by sammy

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

Answer by kadaj

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

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!