note 38045 modified in function.round by didou

From: Date: Wed, 10 Dec 2003 15:49:06 +0000
Subject: note 38045 modified in function.round by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-61746@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. --was-- 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. http://www.php.net/manual/en/function.round.php

« previous php.notes (#61746) next »