Page 1 of 1

[SOLVED] i'm looking for certain floats in for loop

Posted: Thu Apr 19, 2007 9:24 am
by MrPotatoes
something is up with PHP and floats i guess. here is the code that i'm trying to get to work. it's simple enough and should have worked as it does when i'm using integers:

Code: Select all

$t['GUY']	= 20.11;

$test = false;
for ($i = 1.00; $i <= 99.99; $i += 0.01)
{
	//echo $i . '<BR>';
	if ($t['GUY'] == $i)
	{
		$test = true;
		echo 'WE GOT IT!<BR><BR>';
		break;
	}
}
now, when i do it like this it works:

Code: Select all

$t['GUY']	= 50;

$test = false;
for ($i = 1; $i <= 100; $i += 1)
{
	//echo $i . '<BR>';
	if ($t['GUY'] == $i)
	{
		$test = true;
		echo 'WE GOT IT!<BR><BR>';
		break;
	}
}

what is the deal here?

thank you for your help.

Posted: Thu Apr 19, 2007 9:42 am
by pickle
Good question.

I'd say output i on each iteration just to be super sure. Maybe try using the bcmath functions for floating point?

Posted: Thu Apr 19, 2007 9:46 am
by MrPotatoes
let me say that this is PHP4 because that's what i have to do it in.

i am echoing out each number and down the line i'm getting :

91.399999999999
91.499999999999
91.599999999999
91.699999999999
91.799999999999
91.899999999999

WTF?!?!?! this is from adding .01

also, sometime after 1.6 it stops working. this is really frustrating because there is no reason that this shouldn't work.

Posted: Thu Apr 19, 2007 9:49 am
by volka
Please read the Floating point precision paragraph at http://de2.php.net/float

Posted: Thu Apr 19, 2007 10:00 am
by MrPotatoes
i used round in my if check. works just fine now except that i have to count up above the number to be extra clear.

Code: Select all

if ($t['GUY'] == round($i, 2))
{
	$test = true;
	break;
}

Posted: Thu Apr 19, 2007 10:03 am
by pickle
PHP Manual basically wrote:Don't trust floating point precision in PHP - use bcmath if you need 100% proper values
Guess that means one of my summer projects is rewriting some billing software :?


Good to see you got it working.

Posted: Thu Apr 19, 2007 10:24 am
by MrPotatoes
yeah. i new there was an issue with precision once i saw those extra numbers when i scrolled down. sucky thing is that this shouldn't be that big of an issue. whatever though, i got it to work well enough.

it's good to test every little thing that you can. i'm happy i did this sooner than later. i had a feeling that PHP was going to be stupid about this.

thank you guys for the effort though.