Rounding numbers to special values in PHP - e. g. "nice prices"
Sometimes you need to round numbers to special values. Maybe you have a shop and want to calculate your selling prices automatically, but you don't like prices like 12.52 USD.
Here's a small PHP function that can be used in many different ways to solve this problem.
function round_to($number, $step = 1, $sub = 0) { $number += $sub; // to ensure it rounds in the correct way if($step == 0 || $step == 1) return round($number) - $sub; return (round($number / $step) * $step) - $sub; }
This little helper enables rounding to each "nice value" you like to have.
For example:
round_to(12.34, 0.5, 0.01); results in 12.49 (it rounds to the next 0.5-step and reduces by 0.01)
round_to(12.34, 5, 0.01); results in 9.99 (it rounds to the next 5-step value and reduces by 0.01)
round_to(10.7, 2); results in 10.0 (rounds to the next even number)
Of course, you should use other values for big numbers than you use for small ones. For example using a further if-clause:
$x = somenumber; // e. g. your base price $a = $x * 1.2; // 20% margin if($a < 5) $a = $a; // do nothing elseif($a < 10) $a = round_to($a, 0.5, 0.01); elseif($a < 50) $a = round_to($a, 1, 0.01); elseif($a < 150) $a = round_to($a, 5, 0.01); else $a = round_to($a, 10, 0.10);
In this example the price of sale would be:
1.20 USD for a base price of 1.00 USD
12.99 USD for a base price of 11.00 USD (11 * 1.2 = 13.20)
289.90 USD for a base price of 243.34 USD (243.34 * 1.2 = 292.01)
Have fun with "nice prices" ;)