SitePoint Sponsor

# Thread: Is this poor maths or a php bug?

1. ## Is this poor maths or a php bug?

Hello, I have been testing some validation and I cant work out why this isnt working.

PHP Code:
``` \$value_to_check = 25.98; \$value_created_for_check = 19.99 + 5.99; \$value_created_for_check = \$value_created_for_check * 1; // this validation statement fails if (\$value_to_check != \$value_created_for_check) {/*fail validation*/} // but this one passes if (\$value_to_check != round(\$value_created_for_check, 2)) {/*fail validation*/} // but in both validation statements both the values print as 25.98  ```
I am just confused as to why they dont both pass validation, because as far as I can see mathematically speaking 19.99 + 5.99 = 25.98 exactly with no rounding up required?

thanks ro0bear

2. Welcome to floating point math.

3. Floating point representation of numbers in computers are approximate.

PHP Code:
``` echo \$value_to_check - \$value_created_for_check;  ```
Will not print 0, but some really tiny number, which is causing the problem.

Easiest way to prevent this to work in the smallest unit of currency (cents, pennies, or whatever it maybe)

PHP Code:
``` value_to_check = 2598; \$value_created_for_check = 1999 + 599; \$value_created_for_check = \$value_created_for_check * 1;  ```

4. Basically all of the numers in the computer are stored in binary so in oder to do the calculations the decimal values entered are converted to the closest binary equivalents. The calculations are then done and the result converted back to the closest decimal equivalent. The small difference in the expected result is due th the decimal and binary values not being the exact same value (since the computer can only store a certain number of digits).

5. Originally Posted by felgall
Basically all of the numers in the computer are stored in binary so in oder to do the calculations the decimal values entered are converted to the closest binary equivalents. The calculations are then done and the result converted back to the closest decimal equivalent. The small difference in the expected result is due th the decimal and binary values not being the exact same value (since the computer can only store a certain number of digits).
Oh I see, that makes sense now. Thanks everyone for clearing that up, I thought I was going mad lol.

6. If it becomes an issue then you may try BCMath.

7. In case you haven't picked up on this, a basic rule of thumb is don't compare floats.

Read http://us2.php.net/float

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•