Hallo Members,
wenn ich folgenden Befehl ausführe:
round (2.135,2);
dann müsste ja 2.14 rauskommen.
Ich bekomme aber 2.13 raus. Woran kann das liegen?
This is expected behaviour. When rounding on exact halves we round down on evens and up on odds. If you want to always force it in one direction on a .5 (or .135 in your case) add or substract a tiny fuzz factor.
<?php
function myRound($number, $fuzz = 0.00000000001){
return sprintf("%.2f", (($number>=0) ? ($number+$fuzz) : ($number-$fuzz)));
}
echo myRound(1.345);
?>
function myRound($double,$decimals=2){
$tmp = explode(".",doubleval($double));
if(count($tmp)==2 && strlen($tmp[1]) > $decimals){
$fuzz = pow(10,-11);
return sprintf("%.${decimals}f", (($double>=0) ? ($double+$fuzz) : ($double-$fuzz)));
} else {
return doubleval($double);
}
}
Hier mal eine Lösung, die anderen helfen könnte, die das gleiche Prob. haben:
echo round(1.345 + 0.0001, 2);
<?php
function myround($val, $precision = 0) {
$precisionadd = (int) $precision + 2;
$precisionadd = 1 * "1E-$precisionadd";
return round((float) $val + $precisionadd, (int) $precision);
}
echo myround(1.345, 2);
?>
warum? also sowohl meine als auch die round(1.345 + 0.0001, 2);-Lösung runden bei 1,3445 auf 2 und auf 3 stellen vollkommen korrekt!Wiedmann wrote:Alle Lösungen hätten trozdem noch ein Problem mit z.B.: 1.3445
Users browsing this forum: No registered users and 27 guests