A few days ago I was working on a project where it was crucial that all the item prices ended up with a 9 after a discount coupon was redeemed, in need for an quick way to round any given number to the closest nine I did a couple of searches on Google and on the PHP Manual and I found the following formula:
round($number / $nearest) * $nearest;
Seemed pretty much straightforward the only problem is… It didn’t worked as I wanted it to! Imagine that $number is 212 and $nearest is 9 for example, the expected result for this scenario should be 209, since 212 is closer to 209 than to 219. However simple arithmetic tell us that:
round(212 / 9) * 9 = 24 * 9 = 216
Oops, didn’t I asked for the nearest 9? The problem is that this method rounds the number to the nearest multiple, not to the nearest last ending digit(s). To counter-act this problem I’ve made a simple (but not so elegant) PHP function to round to the nearest digit.
Nearest(212, 9); // 209
Nearest(248, 99); // 199
Nearest(249, 99); // 299
P.S.: Please take notice that this function is not as complete as I want it to be, it can only handle positive integers negative integers are now supported.
Heya,
Sorry for not replying to emails, been a bit buzy… I now see what you’re saying, for the negatives just check to see if the string is a negative, change it to a positive, then set it back to a negative once the calculation has been made..
cool blog btw, we definitely share similar interests, datamining/php/security/etc ;]
Mark.
Hey Mark, thank you for your comment.
I was too lazy at the time but I’ve already fixed the issue with negative integers, I haven’t tested it though but should work fine.