I would like to solve rounding mechanism by using php4,5.2 and below (not 5.3) Currently I am doing 0.05 rounding, something like this page:
http://www.bnm.gov.my/in
Expanding a little on @xtofl to allow for more precise steps (not technically required for this question)
$step = 0.0005;
$multiplicand = floor($value / $step);
$rest = fmod($value, $step);
$value = $step * $multiplicand;
if ($rest > $step / 2) {
$value += $step;
}
You basically want to map values to a grid. The grid is defined as a multiple of .05
. In general, you need to find the multiplicands your value lies between.
What isn't in the table are the negative numbers. You need to decide on whether to round away from zero (symmetrical) or always in the same direction (i.e. positive).
code:
$step = .05;
$multiplicand = floor( $value / $step );
$rest = $value % $step ;
if( $rest > $step/2 ) $multiplicand++; // round up if needed
$roundedvalue = $step*$multiplicand;
Conceptually, the procedure can be done as:
function round5Sen ($value) {
return number_format(round($value*20,0)/20,2,'.','');
}
echo round5Sen(155.13);
echo "\n";
echo round5Sen(155.12);
echo "\n";
echo round5Sen(155.0);
echo "\n";
echo round5Sen(155.18);
echo "\n";
Thank you @mauris for the solution to solve my problem on Malaysia GST rounding mechanism. It also works in SQL.
DECLARE @tempTable AS TABLE(Number Decimal(20,4));
INSERT INTO @tempTable VALUES (89.90),(89.91),(89.92),(89.93),(89.94),(89.95),(89.96),(89.97),(89.98),(89.99)
SELECT Number, round(Number * 2, 1) / 2 AS 'Rounded' FROM @tempTable
Multiply by two, then round, then divide by two.