note 108046 added to function.floor
| From: | clchuah at apic dot com dot sg | Date: | Sat, 24 Mar 2012 08:37:18 +0000 |
| Subject: | note 108046 added to function.floor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186803@lists.php.net to get a copy of this message | ||
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 !!!
----
Server IP: 124.217.228.174
Probable Submitter: 110.159.131.36
----
Manual Page -- http://www.php.net/manual/en/function.floor.php
Edit -- https://master.php.net/note/edit/108046
Del: integrated -- https://master.php.net/note/delete/108046/integrated
Del: useless -- https://master.php.net/note/delete/108046/useless
Del: bad code -- https://master.php.net/note/delete/108046/bad+code
Del: spam -- https://master.php.net/note/delete/108046/spam
Del: non-english -- https://master.php.net/note/delete/108046/non-english
Del: in docs -- https://master.php.net/note/delete/108046/in+docs
Del: other reasons-- https://master.php.net/note/delete/108046
Reject -- https://master.php.net/note/reject/108046
Search -- https://master.php.net/manage/user-notes.php