note 38045 deleted from function.round by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 16:24:32 +0000 |
| Subject: | note 38045 deleted from function.round by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-154820@lists.php.net to get a copy of this message | ||
Note Submitter: ssttoo at hotmail dot com
----
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.