Are floats smaller than integers?

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
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Are floats smaller than integers?

Post 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?
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Re: Are floats smaller than integers?

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

Re: Are floats smaller than integers?

Post by pickle »

If founding is an issue, look into the bc_math functions.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
allspiritseve
DevNet Resident
Posts: 1174
Joined: Thu Mar 06, 2008 8:23 am
Location: Ann Arbor, MI (USA)

Re: Are floats smaller than integers?

Post 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.
Post Reply