Page 1 of 1

Are floats smaller than integers?

Posted: Thu Jun 18, 2009 1:46 pm
by allspiritseve
I have a variable $cases in my code. If I do this:

Code: Select all

var_dump($cases);
var_dump($cases >= 1);
it produces:

Code: Select all

float(1)
bool(false)
What is going on??? I am so confused. $cases should equal 1, since it equals 1.0. Right?

Re: Are floats smaller than integers?

Posted: Thu Jun 18, 2009 2:12 pm
by allspiritseve
Ah, I figured it out. It's a rounding error on PHP's part. I am adding 2/12 6 times, which apparently rounds somewhere and is just under 1.0

Re: Are floats smaller than integers?

Posted: Thu Jun 18, 2009 2:27 pm
by pickle
If founding is an issue, look into the bc_math functions.

Re: Are floats smaller than integers?

Posted: Fri Jun 19, 2009 12:04 pm
by allspiritseve
Hmm... I don't know if that would help or not. I fixed my code by working with numerators/denominators rather than dividing and working with floats.

I'm actually considering writing a little value object that works with fractions:

Code: Select all

$fraction = new Fraction('2/4');
$fraction->add(new Fraction('3/11'));
$fraction->subtract(new Fraction('1/6'));
$fraction->getFloat();
$fraction->getFraction();
Which would make calculations like these simple, since it will work with numerators and denominators internally and then convert to a float only when needed.