Thursday, January 5. 2006Banker's Rounding for PHPTrackbacks
Trackback specific URI for this entry
No Trackbacks
Comments
Display comments as
(Linear | Threaded)
Nice, but shame it's GPL'd. I wanted something like this for a webhosting billing system I'm working on, but there's no way I could release the source code (it's full of proprietary code I'm not permitted to disclose)...
Oh well
GPL seems a fair way to let people share code. If you have a need to use the code in a commercial project, we can make other licensing arrangements if you'd like.
Quick note - if you just want to round to a whole number (i.e, you don't need decimal precision), it's suddenly a lot easier:
function bround($num) { return (($num & 1) ? ceil($num) : floor($num)); } Hope this helps someone.
Thanks for the post. I don't think your code quite does banker's rounding. Banker's rounding should only alternate the even/odd round up/down when the digit in question is a 5, not for all cases. In your code, 0.1 through 0.9 all round down to 0, and 1.1 to 1.9 all round up to 2.
If I understand banker's rounding correctly, 0.1 to 0.5 all round down to 0, and 0.6 to 0.9 round to 1. Then 1.1 to 1.4 round down to 1, and 1.5 to 1.9 round to 2. I do like the bitwise test you did for even/odd, so I replaced the modulus test I was using with it. I ran some PHP tests and on my system, the bitwise test was nearly a second faster than the modulus test through 1E7 iterations.
For video encoding I needed a function that rounds any number to a whole even number. Google couldn't help so I came up with this:
function is_odd($num) { return $num % 2; } function make_even($num) { if(is_odd(floor($num))) { $return = ceil($num); } else { $return = floor($num); } if(is_odd($return)) { $return -= 1; } return $return; } 3.1 rounds to 4 2.9 rounds to 2 3.0 rounds to 2 If you need 3 to round to 4 change the 4th last line to $return += 1; |
CategoriesQuicksearchArchives |