Error Calculating With Decimals

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ShannyMan
Forum Newbie
Posts: 9
Joined: Thu Sep 17, 2009 7:46 am

Error Calculating With Decimals

Post 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!
ShannyMan
Forum Newbie
Posts: 9
Joined: Thu Sep 17, 2009 7:46 am

Re: Error Calculating With Decimals

Post by ShannyMan »

The solution to this was to avoid using fractional numbers, and instead, using this:

$price = $stockingPrice * 10 / 7;
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Error Calculating With Decimals

Post by John Cartwright »

You generally want to use the bc math functions when dealing with prices, otherwise you'll end up with unusual roundings.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Error Calculating With Decimals

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Error Calculating With Decimals

Post 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
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply