I found this code on php.net which works for me for the round_up part..
function round_up($value, $precision = 0) {
if (!empty($value)) {
$sign = (0 <= $value) ? +1 : -1;
$amt = explode('.', $value);
$precision = (int) $precision;
if (strlen($amt[1]) > $precision) {
$next = (int) substr($amt[1], $precision);
$amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);
if (0 != $next) {
if (+1 == $sign) {
$amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign);
}
}
}
else {
$amt[1] = (float) (('.'.$amt[1]) * $sign);
}
return $amt[0] + $amt[1];
}
else {echo 'error';}
}
Added a couple minus's.. to get this one...
function round_down($value, $precision = 0) {
if (!empty($value)) {
$sign = (0 <= $value) ? +1 : -1;
$amt = explode('.', $value);
$precision = (int) $precision;
if (strlen($amt[1]) > $precision) {
$next = (int) substr($amt[1], $precision);
$amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign);
if (0 != $next) {
if (-1 == $sign) {
$amt[1] = $amt[1] - (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign);
}
}
}
else {
$amt[1] = (float) (('.'.$amt[1]) * $sign);
}
return $amt[0] + $amt[1];
}
else {echo 'error';}
}
Is there any better way to do it? (I only require it for positive decimals) Currently for the most part it works without much glitches..
$azd = 0.0130;
$azd1 = number_format(round_up($azd,2),4);
$azd2 = number_format(round_down($azd,2),4);
$azd3 = number_format(round_up($azd,1),4);
$azd4 = number_format(round_down($azd,1),4);
echo 'Round_up = '.$azd1.'<br>'; // 0.0200
echo 'Round_down = '.$azd2.'<br>'; // 0.0100
echo 'Round_up = '.$azd3.'<br>'; // 0.1000
echo 'Round_down = '.$azd4.'<br>'; // 0.0000
function round_up($value, $precision=0) {
$power = pow(10,$precision);
return ceil($value*$power)/$power;
}
function round_down($value, $precision=0) {
$power = pow(10,$precision);
return floor($value*$power)/$power;
}