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);
July 22, 2010

Working with decimal numbers in PHP

Question by The Worst Shady

I want to somehow round the numbers for a rating system in PHP like this:

4.6667 = 4.6

5.0001 = 5.0

Is there any way to do that? (BTW, I read the data from a database.)

Answer by Sarfraz

You are not conforming to any single rule. For example:

4.6667 = 4.6
5.0001 = 5.1

See these functions anyway:

round
ceil
floor

And number_format.

Answer by Starx

Use this:

echo round(1.45667, 2);

The number “2” is how many decimal places you want.

This is output 1.46.

...

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