Question:
The following problem occurred. We need a function to round the number up to hundredths. Initially, the function looked like this:
function round_up($value, $precision) {
$pow = pow ( 10, $precision );
return ceil($value * $pow) / $pow;
}
but there was a problem when passing the next value round_up(740*0.006,2)
to the function, it gives 4.45 instead of 4.44. Further, the function was corrected in the following form:
function round_up ( $value, $precision ) {
$pow = pow ( 10, $precision );
return ceil(round($value * $pow,2)) / $pow;
}
I solved the previous problem, but a new one also appeared when passing the next value to the function:
round_up(3208.34*0.006,2)
it gives 19.25 instead of 19.26. Maybe someone has already encountered this? Thanks a lot in advance!!!
Answer:
Try this:
function round_up ( $value, $precision ) {
$pow = pow ( 10, $precision );
return round($value * $pow + 0.49999999999) / $pow;
}
Then, the first function you have given works correctly, but the error occurs due to the calculation error. I think that pow ( 10, 2.0 )
will give not exactly 100, but something like 100.000001 If you need to round strictly to 2 characters, try
function round_up($value) {
return ceil($value * 100) / 100;
}