Severe Error in PHP Language

Asked

Viewed 55 times

2

I discovered a BUG in the php language and I’m looking for a logical explanation for this, I have the following Code:

<?php
    echo (int) ((0.1 + 0.7) * 10);
?>

And the result shown is: 7. Why is this? a php bug?

take the test: http://phpio.net/s/ryn

  • 4

    This is not a bug it’s a Feature. This is a rounded float. This question is a duplicate.

  • 4

    This is not unique to PHP, but a floating point problem: What Every Computer Scientist Should Know About Floating-Point Arithmetic

  • You can send the @Inkeliz link

  • 3

    PHP is used by millions of people every day and several years ago. If there was such a bug, it would have been fixed long ago. Before you think any strange behavior is a bug, do some research on why these things happen. You’ll learn a lot about things you never imagined existed and become a better programmer ;)

2 answers

3


On your question the expression ((0.1 + 0.7) * 10) should evaluate to 8.

However, the output of the expression in the script is evaluated at 7 because the PHP engine stores the expression value internally as 7.999999 instead of 7.

When the fractional value is converted to an integer, the PHP engine simply truncates the fractional part.

When the value is converted to int, PHP simply truncates the fractional part, resulting in a fairly significant error (12.5%, to be exact).

1

It is not a PHP BUG logically, but because you are doing a cast (int) so floating point values are rounded to more or less significant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.