Error Calculating with Decimals

Login or register to post comments
2 replies [Last post]
Offline
Joined: 06/25/2009

I feel a bit odd/special/dumb since half of the topics in this forum are from me. Maybe I'm the only one that runs into these issues. ;)

I'm running into a very strange issue where very cut and dry math is getting distorted by PHP. Here's the function:

private function GetListPrice($stockingPrice)
{
$price = $stockingPrice / .7;
$decimal = $price - floor($price);

if ($price > 100)
return ceil($price);
else
{
if ($decimal <= .5)
return floor($price) + .5;
else
return floor($price) + 1;
}
}

If I give this function a value of 175, it returns 251. It should be 250 (175 / .7 = 250). When I look at it with the debugger, $stockingPrice = 175, $price = 250 but $decimal is 2.8421709430404E-14, which is causing the ceiling function to return 251.

Any ideas why this is happening? It's jacking up our pricing! Thanks!

Offline
Joined: 03/31/2008

Unfortunately, that's just how computers represent numbers internally. You may want to try and avoid floating point (fractional) numbers whenever possible by doing this instead:

<?php
$price
= $stockingPrice * 10/7;
$decimal = $price - floor($price);
?>

In addition, you may want to account for floating point imprecision by only using ceil if $decimal is > 0.0000001, and otherwise using floor;

Prinz Bernhard's picture
Offline
Joined: 04/11/2010

or better do a rounding.

<?php
     $price
= round ( $stockingPrice/0.7 , 2 ) ;
?>

So you are sure, not to get unwanted fractions.

As VexedPanda said, it has to to with number representation of floats.
You don“t have the datatype decimal (16,2) in PHP.

http://en.wikipedia.org/wiki/Floating_point