Forum Moderators: coopster

Message Too Old, No Replies

Simple dollar / math problem, how to stop rounding?

         

Sgt_Kickaxe

4:42 am on May 16, 2010 (gmt 0)



I have a simple math / money related feature running in php and can't seem to get it running properly.

I set an average price figure - $avgprice = 5.55;
I find the price of an item - $itemprice = $valuefromsource;
I figure out the saving - $saving = $avgprice - $itemprice;

The end result is always the same (and wrong). For whatever reason the $saving parameter SEES the $avgprice correctly and $itemprice correctly but when working out $saving it DROPS the numbers after the decimal. In other words 2.75 becomes 2.00 and it spits out a $saving of 3.55 when it's only 2.80. I triple checked and performed a var_dump for each parameter and they're all fine, it's only during calculation of $saving do things get odd.


$avgprice = 5.55;
$itemprice = 2.25;
$saving = $avgprice - $itemprice;

It SHOULD say the savings are 3.30 in this example but I get 3.55. The .25 is stripped. What am I doing wrong ?

Readie

9:37 am on May 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've had this problem with floats before. Try defining them in quotes:

$avgprice = '5.55';
$itemprice = '2.25';

dreamcatcher

2:31 pm on May 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sgt_Kickaxe, I ran your code and it returned 3.3 as expected. What PHP version are you using?

dc

rocknbil

5:51 pm on May 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Agreed, there's something else going on there, try isolating that in a small script all by itself, it will result in 3.3.

the savings are 3.30


// presuming you have 3.3,
echo sprintf("%.2f",$savings);
// --> 3.30

Only use sprintf on printouts, not in calculations.

Slightly OT, because this is not the problem, or shouldn't be: floating point issues are largely O.S. dependent, and you will get some odd results in some cases having to do with floating point precision. One way to get around it with some degree of accuracy:

$price = 12.95;
$quan = 4;
$tot = sprintf("%.2f",intval($quan * $price * 100)/100);
echo $tot;

I've found this pops up much more in Javascript than in any other language, due to much of it being input from text fields which are strings.