I am trying to make an algorithm that will round according to these conditions:
- 1 or 2 cents - rounded down to "0"
- 3 or 4 cents - rounds up to 5 cents
- 5 cents - 5 cents left
- 6 or 7 cents - rounds down to 5 cents
- 8 or 9 cents - rounds up to "0"
So, it should look like this:
PRICE| AFTER
9.90 | 9.90
9.91 | 9.90
9.92 | 9.90
9.93 | 9.95
9.94 | 9.95
9.95 | 9.95
9.96 | 9.95
9.97 | 9.95
9.98 | 10.0
9.99 | 10.0
10.0 | 10.0
My code is here, but looks strange. For numbers like 10.99 result becomes 10.10:
function roundDown(float $price): float
{
[$number, $decimals] = explode('.', sprintf('%.2f', $price));
[, $second] = str_split($decimals);
$table = [
0 => 0,
1 => -1,
2 => -2,
3 => 2,
4 => 1,
5 => 0,
6 => -1,
7 => -2,
8 => 2,
9 => 1,
];
return $number . '.' . str_pad((float)$decimals+(float)$table[$second], 2, '0', STR_PAD_LEFT);
}
Thanks in advance.
.05. So feeding a whole number would just spit back the whole number, if your code is working as your requirements describe. Can you share what your expected output of a number-without-decimal would be?