Friday, September 19, 2014

The Ultimate Rounding Function

Your search for any requirement for rounding function is over. You need to round amount to quarter? dime? nickel? penny? a dollar? 10 dollar? Below function of single linen can provide you more than what you are looking for. for sure!
 decimal NearestOfPenny(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 0.01m, 0.5m);
 }

 decimal NearestOfNickel(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 0.05m, 0.5m);
 }

 decimal NearestOfDime(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 0.10m, 0.5m);
 }

 decimal NearestOfQuarter(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
 }

 decimal NearestOfDollar(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 1m, 0.5m);
 }

 decimal UpwardDollarOnlyIfReminderIsMoreThan70Cents(decimal amountToRound)
 {
     return UltimateRoundingFunction(amountToRound, 1m, 0.3m); 
     //i.e. 0.70 will round up. but 0.69 will be rounded to 0.. this magic is from value of 'fairness'.
 }
 
 //amountToRound => input amount
 //nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1
 //fairness => btween 0 to 0.9999999___. 
 //            0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling
 //            0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1.
 //            0.4999999... Non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2.
 //            0.75 means first 75% values will be rounded down, rest 25% value will be rounded up.
 decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness)
 {
     return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf;
 }