-1

When i run the following PHP Script which is just calculating the discount of 30% from 11.5. I'll get some strange result. Normally i would expect the condition to be false when testing the calculated result. But instead i get true.

Whats wrong with php in this case?

<?php
$_discount = 30;
$_price = 11.5;
$_qty = 1;

echo $_result = ((1-$_discount / 100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05;
echo gettype($_result); // prints double

echo $_result !== 8.05; // returns 1 instead of 0
?>
  • 1
    Please use [`gmp()`](http://www.php.net/manual/en/ref.gmp.php) functions for float operations. – Shankar Narayana Damodaran Apr 22 '14 at 10:01
  • There have been a lot of questions on SO about comparing floats: [this](http://stackoverflow.com/questions/3148937/compare-floats-in-php) and [this](http://stackoverflow.com/questions/3148937/compare-floats-in-php) are just 2 examples. Please see [php.net](http://www.php.net/manual/en/language.types.float.php) – Paul Blundell Apr 22 '14 at 10:26

1 Answers1

2

Try to use this:

<?php
$_discount = 30;
$_price = 11.5;
$_qty = 1;

echo $_result = ((1-$_discount / 100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05;
echo gettype($_result); // prints double

echo (double)$_result !== 8.05;
?>
Alexey Palamar
  • 1,440
  • 1
  • 10
  • 16