note 38045 added to function.round

From: Date: Fri, 05 Dec 2003 21:12:49 +0000
Subject: note 38045 added to function.round
Groups: php.notes 
Request: Send a blank email to php-notes+get-61465@lists.php.net to get a copy of this message
Having done the following test: <?php $test_numbers = array (1.255,3.255,10.255); foreach ($test_numbers AS $number){ echo "<br />Number:<b> " . $number . "</b>"; echo "<br />Printf():<b> "; printf("%.2f",$number); echo "</b><br />Printf() and round(): <b> "; printf("%.2f",round($number,2)); echo "</b><br />Printf() and round() *100/100:<b> "; printf("%.2f",round($number*100)/100); echo "</b><br />----------------"; } ?> it looks that small numbers are not always rounded the way one expects, regardless of the rounding method used. The results are: Number: 1.255 Printf(): 1.25 Printf() and round(): 1.25 Printf() and round() *100/100: 1.25 ---------------- Number: 3.255 Printf(): 3.25 Printf() and round(): 3.25 Printf() and round() *100/100: 3.26 ---------------- Number: 10.255 Printf(): 10.26 Printf() and round(): 10.26 Printf() and round() *100/100: 10.26 So to get around this I came out with a small 'fuzz'-ing: <?php function myFormattedRoundedNumber($number, $fuzz = 0.00000000001){ return sprintf("%.2f", (($number>0) ? ($number+$fuzz) : ($number-$fuzz))); } ?> As you can see, it also takes into account the negative numbers. ---- Manual Page -- http://www.php.net/manual/en/function.round.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+38045 Delete -- http://master.php.net/manage/user-notes.php?action=delete+38045&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+38045&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#61465) next »