I have this code
I want to round two decimals to half up, I expect a value as 0.58... but
if you expect 0,58 you don't have to use a "half round" but the ceil function
$v = 0.575;
echo ceil($v * 100) / 100; // show 0,58
The value 0.572
can not be rounded up to 0.58
, because the third decimal, 2
, is less than half (or 5
). If you were doing round(0.575, 2, PHP_ROUND_HALF_UP)
you would get 0.58
. In this case 0.57
is the correct rounded value.
If you wish to always round up from the 3rd decimal, regardless of its value you could use ciel()
instead, but it requires a little additional math. A simple function to demonstrate rounding up always would be...
function forceRoundUp($value, $decimals)
{
$ord = pow(10, $decimals);
return ceil($value * $ord) / $ord;
}
echo forceRoundUp(0.572, 2); // 0.58
echo forceRoundUp(0.57321, 4); // 0.5733
function round_up($value, $places)
{
$mult = pow(10, abs($places));
return $places < 0 ?
ceil($value / $mult) * $mult :
ceil($value * $mult) / $mult;
}
echo round_up(0.572,2);
Hope this will work for you!!