June 8, 2023

Sometimes 7 and 8 are equal.

Back in college I had a professor who would dock off points every time he saw the word float in our code. He never really told us why, but from then on we all started using double any time we needed a decimal.

It’s been a few years since college, but I think I’m finally closer to understanding what he meant. Take a look at the following PHP code. What do you think it does?

echo (int) ((.1 + .7) * 10);

It’s a basic PHP math operation. It should add .1 and .7 to get .8, then multiply that by 10 to yield 8 right?

Not so fast, what’s that (int) doing?

For those of you unfamiliar with PHP, it’s a dynamicaly typed language. That means unlike c++, you don’t have to declare a type when you declare a variable. PHP will look at how you’re using it and decide what you meant.

The (int) is a cast. It tells PHP to take whatever that result is and make sure it’s an integer. It’s very seldom used, but there are a few examples I can think of where it’s a good idea to cast your variables. I’ll save that for a later column though.

Anyway, run the above code. What happens? Do you see 8? No! It outputs 7!!

Take the (int) cast away though, and you’ll see your expected result.

So what’s going on here? The simple answer is that it has something to do with the way PHP handles floating point numbers. The long answer is, it’s the reason why the data from one of my applications never added up correctly.

About Ryan Jones

Ryan Jones is an SEO from Detroit. By day he works as a manager of SEO & Analytics at SapientNitro where his team performs SEO for Fortune500 clients. By night he's either playing hockey or attempting to take over the world with his own websites - which he would have already succeeded in doing had it not been for those meddling kids and their dog. The views expressed here have not been paid for and belong only to Ryan, not any of his employers or clients. Follow Ryan on Twitter at: @RyanJones, add him on Google+ or visit his personal website: www.RyanMJones.com