0

In testing with cash conversions I ran into this. If I set the 510 to intval() it still says that the float * 100 is less than the string or int. Why does php do that?

$var = 4.73 + .37;
$amt = 510;
if($var * 100 > 510){
    echo 'wtf';
}
Case
  • 4,122
  • 5
  • 33
  • 50
  • 4
    Welcome to floating point arithmetic. – Sirko Feb 17 '14 at 10:02
  • place var_dump( $var, $amt ); before the if statement. You'll find your answer there. –  Feb 17 '14 at 10:03
  • 3
    http://floating-point-gui.de/ Read it. And don't use floating point ever anymore for money. Use an int and count cents. – Bart Friederichs Feb 17 '14 at 10:05
  • This question already exist, [here](http://stackoverflow.com/questions/5230305/php-integer-and-float-comparison-mismatch), and the answer is in the [PHP Manual - Floating point numbers](http://php.net/manual/en/language.types.float.php) - see red big warning box. – Pixic Feb 17 '14 at 10:12

1 Answers1

5

it's all about floating point arithmetic. The same problem occurs in every other programming language

the simplest example: 0.1 + 0.2 = 0.30000000000000004

you won't see it if you use echo or even var_dump because it will be truncated to show in a human friendly form, but you can see it clearly here:

$a = 0.3; // true 0.3
$b = 0.1 + 0.2; // approximately 0.3

var_dump($a); // 0.3
var_dump($b); // 0.3

var_dump($a == $b); // false

var_dump($a == 0.3); // true
var_dump($b == 0.3); // false

var_dump($a == 0.30000000000000004); // false
var_dump($b == 0.30000000000000004); // true

Don't use floats to store money amount and especially to do any calculations on them - use cents or fixed point arithmetic (if applicable)

Adassko
  • 4,689
  • 18
  • 35