I have this code :
<?php
$a = 991.3;
$float = floor($a);
$float = $a - $float;
echo $float;
it gives me this as result:
0.29999999999995
why not 0.3
? and how to get 0.3
instead of 0.29999999999995
?
I have this code :
<?php
$a = 991.3;
$float = floor($a);
$float = $a - $float;
echo $float;
it gives me this as result:
0.29999999999995
why not 0.3
? and how to get 0.3
instead of 0.29999999999995
?
This is because PHP's precision with floating point numbers is not exact. This is warned of in the php manual entry about floating point number.
If you want mathematical precision for different operations, you must use PHP's bcmath
extension. I bet it must be compiled already in your PHP installation, but if not, you can always google how to install it. :)
These are the functions you want to use.
You can use this PHP functions for doing operations with precisions number.
<?php
$a = '1.234';
$b = '5';
echo bcsub($a, $b); // -3
echo bcsub($a, $b, 4); // -3.7660
?>