note 108046 deleted from function.floor by googleguy
| From: | googleguy@php.net | Date: | Sat, 19 Jan 2013 03:48:36 +0000 |
| Subject: | note 108046 deleted from function.floor by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193255@lists.php.net to get a copy of this message | ||
Note Submitter: clchuah at apic dot com dot sg
----
I have this little truncate float function
function truncate1 ($num, $digits = 0) {
$shift = pow(10 , $digits);
return ((floor($num * $shift)) / $shift);
}
I hit a weird floor() behavior problem recently, it took very long time to debug, see this:
$e_num = 25/24;
echo $e_num." orig\n"; // get 1.0416666666667
$rnd = round($e_num, 6);
echo $rnd." round\n"; // get 1.041667
$trc = truncate1($rnd, 6);
echo $trc." truncate\n"; // get 1.041666 !! expected 1.041667
$mul = $rnd * 1000000;
echo $mul." multiply\n"; // get 1041667
$flr = floor($mul);
echo $flr." floor\n"; // get 1041666, expected 1041667
I think because $rnd is kept as float so it's not precisely 1.041667. So i tested this further
$flr1 = floor(1.041667 * 1000000);
echo $flr1." floor1\n"; // get 1041666
$flr2 = floor(1041667);
echo $flr2." floor2\n"; // get 1041667
So beware of float type !!!