Why?

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
jkjasonkellar
Forum Newbie
Posts: 1
Joined: Fri Dec 26, 2008 11:57 am

Why?

Post by jkjasonkellar »

Why does this evaluate to 7?

Code: Select all

echo (int) ((0.1 + 0.7) * 10);
I was told it is because (0.1 + 0.7) * 10) is being stored as 7.99999999, and everything after the decimal is cut off by the conversion to int, but why is it being stored as that? Surely ((0.1 + 0.7) * 10) should be being stored as 8 even before the data type conversion?
cptnwinky
Forum Commoner
Posts: 84
Joined: Sat Dec 27, 2008 10:58 am
Location: Williamstown, MA

Re: Why?

Post by cptnwinky »

I don't know why either but typecasting it as float makes it work out right.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Why?

Post by Mark Baker »

jkjasonkellar wrote:Why does this evaluate to 7?

Code: Select all

echo (int) ((0.1 + 0.7) * 10);
I was told it is because (0.1 + 0.7) * 10) is being stored as 7.99999999, and everything after the decimal is cut off by the conversion to int, but why is it being stored as that? Surely ((0.1 + 0.7) * 10) should be being stored as 8 even before the data type conversion?
Nope, the values 0.1 and 0.7 are floating point values, and the result of the sum (0.8) is a floating point value. When you multiply that by 10, despite 10 being an integer, the result is also still a floating point value until it is cast to integer.

Try doing:

Code: Select all

echo round((0.1 + 0.7) * 10);
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Why?

Post by Chris Corbyn »

Note that round() also returns a floating point value ;)
Post Reply