Did I find a php bug?

Maybe today I found a php bug… try to run this script on your server…

1
2
3
4
5
6
7
8
<?php
 
$a=100.9;
$b = 100;
$c = $a-$b;
echo $c;
 
?>

What do you get?

I get a 0.90000000000001 on different servers with different php installations

Am I the only one?

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 11 comments

  1. eels

    on January 12, 2007 at 9:55 pm

    No, you didn’t: http://www.php.net/float

    ….
    So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.
    ….

  2. sinatosk

    on January 12, 2007 at 10:04 pm

    no your not the only one :p. I’m using php 5.1.6

  3. Josh

    on January 13, 2007 at 2:18 am

    That’s pretty common in many languages. I’ve encountered this behavior in Flash a few times too. It happens because floating point math isn’t completely accurate, and mathematical operations can cause you to lose precision. It’s not really the language, but the computer architecture.

  4. Xera

    on January 18, 2007 at 2:57 pm

    That’s not a bug, http://php.net/float

    Xera

  5. V34

    on February 17, 2007 at 5:58 pm

    Of what I remember it has something to do with this.
    http://en.wikipedia.org/wiki/0.999

    Hope it’s OK I testes the BBCodes.
    [code]Test[/code][b]Test[/b][url]http://test.dk[/url]

  6. ben

    on November 28, 2007 at 5:48 am

    I am taking programming languages class this semester. We are writing our programming language, compiler, interpreter so on. this is not a bug. I dont want to get depth about p.l. but I can say that php doesnt have data types. it allows you really flexible features, but if you are making calculations you have to handle your data

  7. Shadow Scythe

    on December 1, 2007 at 12:28 pm

    If it becomes a problem in programming, try using Math.round. And in your case, since you’re using tenths, try Math.round($a*10)/10. Hopefully that’ll fix it.

  8. shedokan

    on January 25, 2008 at 5:19 pm

    I get 0.9 with xampp server

  9. Dale Hay

    on February 3, 2008 at 4:01 am

    I have tested it on my localhost (Using Apache, PHP & MySQL… *cough* AppServ *cough*) and mine reads 0.9 as the answer. :D

  10. bob

    on February 6, 2008 at 7:55 pm

    Actually, the 1 just shows it’s repeating. Like on a calculator it shows .00000001 or .111111112 or .2222222223, etc.

  11. shaman4d

    on May 13, 2009 at 6:15 pm

    This is bug not only in php, it is number round bug in all programming languages with float point math.