Tuesday, February 21, 2006

.Net 1.1 and System.Math.Round -- Banker's Round and .5

The provided Math.Round function implements "bankers rounding", which rounds to the nearest even number when a number ends in .5
 
This means that both 1.5 and 2.5 round to 2.  This is not what most e-commmerce and real-world implementations need.  Here is a "normal" or "US round" function.
 
 
/// <summary>
/// Rounds the specified to round.
/// </summary>
/// <param name="toRound"> To round.</param>
/// <param name="digits"> The digits.</param>
/// <returns></returns>
namepsace MathUtils {
 public static decimal Round( decimal toRound, int digits ) {
   toRound *= (decimal )(Math.Pow(10d,(double)digits));
   if( toRound - Decimal.Truncate(toRound) >= .5m ) {
      toRound += 1;
   }
   toRound = Decimal.Truncate(toRound);
   toRound /= (decimal)( Math.Pow(10d,(double)digits));
   return toRound;
 }
}

No comments: