2

Today i started writing a small PHP code and it left me confusing and so i parked here.

<?php
echo (int) ((0.5 + 0.3) * 10); // Outputs 8 as expected

<?php
echo (int) ((0.1 + 0.7) * 10); // Outputs 7 . How ????

Can someone answer with a detailed explanation ?

  • 1
    Welcome to the world of floating point on computers – Mark Baker Sep 10 '13 at 06:57
  • aaah, the joy of floating numbers ( 0.7 is actually something like 0.69999999999999 ) - edit: and casting in php? isnt this somekind of looked down on? I mean most people argue that type-free is the most awfsome ( awfull + awesome ) thing in php – Najzero Sep 10 '13 at 06:57
  • See http://stackoverflow.com/questions/6439140/int0-10-710-7-in-several-languages-how-to-prevent-this for detailed answer. –  Sep 10 '13 at 06:58
  • echo (int) (0.1 + 0.7) * 10; – DevZer0 Sep 10 '13 at 06:59
  • I find this one: http://floating-point-gui.de/ better than the Oracle one. – Bart Friederichs Sep 10 '13 at 07:00

1 Answers1

2

It is because floating point representation in computers is not exact for some numbers. As already said in the comments, 0.7 is represented internally as 0.699999 or so.

There are two websites that continuously pop up in these kind of questions:

  1. http://floating-point-gui.de/
  2. http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

I prefer the first one, as it is a little lighter on the academics. Read that information and you'll understand.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195