Skip to content

Instantly share code, notes, and snippets.

@boone
Created January 17, 2016 13:47
Show Gist options
  • Save boone/9c887899ae294adb097c to your computer and use it in GitHub Desktop.
Save boone/9c887899ae294adb097c to your computer and use it in GitHub Desktop.
<?php
/*
Banker's Rounding v1.01, 2006-08-15
Copyright 2006 Michael Boone
mike@Xboonedocks.net (remove the X)
http://boonedocks.net/
Provided under the GNU General Public License
Contact me for use outside the bounds of that license
---------------------------------------------------------------
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
The GNU General Public License can be found at:
http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------
Release History:
2006-01-05: v1.00: Initial Release
2006-08-15: v1.01: Updated with faster even/odd test
*/
function bround($dVal,$iDec) {
// banker's style rounding or round-half-even
// (round down when even number is left of 5, otherwise round up)
// $dVal is value to round
// $iDec specifies number of decimal places to retain
static $dFuzz=0.00001; // to deal with floating-point precision loss
$iRoundup=0; // amount to round up by
$iSign=($dVal!=0.0) ? intval($dVal/abs($dVal)) : 1;
$dVal=abs($dVal);
// get decimal digit in question and amount to right of it as a fraction
$dWorking=$dVal*pow(10.0,$iDec+1)-floor($dVal*pow(10.0,$iDec))*10.0;
$iEvenOddDigit=floor($dVal*pow(10.0,$iDec))-floor($dVal*pow(10.0,$iDec-1))*10.0;
if (abs($dWorking-5.0)<$dFuzz) $iRoundup=($iEvenOddDigit & 1) ? 1 : 0;
else $iRoundup=($dWorking>5.0) ? 1 : 0;
return $iSign*((floor($dVal*pow(10.0,$iDec))+$iRoundup)/pow(10.0,$iDec));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment