Page 1 of 1

Error Calculating With Decimals

Posted: Thu Apr 22, 2010 10:38 am
by ShannyMan
I'm running into a very strange issue where very cut and dry math is getting distorted by PHP. Here's the function:

Code: Select all

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!

Re: Error Calculating With Decimals

Posted: Thu Apr 22, 2010 12:19 pm
by ShannyMan
The solution to this was to avoid using fractional numbers, and instead, using this:

$price = $stockingPrice * 10 / 7;

Re: Error Calculating With Decimals

Posted: Thu Apr 22, 2010 4:44 pm
by John Cartwright
You generally want to use the bc math functions when dealing with prices, otherwise you'll end up with unusual roundings.

Re: Error Calculating With Decimals

Posted: Thu Apr 22, 2010 6:23 pm
by requinix
Since floating-point errors are typically very small, I use round before (or instead of) floor() or ceil(). Round to the second or third decimal place past the degree of precision you need.

Re: Error Calculating With Decimals

Posted: Fri Apr 23, 2010 9:54 am
by pickle
John Cartwright wrote:You generally want to use the bc math functions when dealing with prices, otherwise you'll end up with unusual roundings.
+1