Mercurial > repos > IBBoard
changeset 34:d597feec5dd4
Closes #20 - Add rounding method with enum
* Add RoundType enumeration with up, down, 'banker', up to half, down to half, 'banker' to half
* Add IBBMath.Round(double, RoundType)
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Tue, 19 May 2009 14:24:00 +0000 |
parents | 8971a1c48dbf |
children | 2b5e73cb83a3 |
files | Lang/IBBMath.cs |
diffstat | 1 files changed, 61 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/Lang/IBBMath.cs Sun May 17 19:22:53 2009 +0000 +++ b/Lang/IBBMath.cs Tue May 19 14:24:00 2009 +0000 @@ -7,6 +7,24 @@ namespace IBBoard.Lang { + /// <summary> + /// RoundType defines how a number should be rounded. "Up" always rounds up (Ceiling), "Down" always rounds down (Floor), "Banker" rounds + /// up or down as appropriate with a balanced bias (rounding towards even). Each rounding method also has a "ToHalf" version that performs + /// the same type of rounding, but to the closes half number instead of the closest whole number. + /// </summary> + public enum RoundType + { + Up, + Down, + Banker, + UpToHalf, + DownToHalf, + BankerToHalf + } + + /// <summary> + /// IBBMath provides a number of custom Maths functions based on the core Math classes. + /// </summary> public class IBBMath { /// <summary> @@ -51,5 +69,48 @@ { return Math.Ceiling(number * 2) / 2; } + + /// <summary> + /// Returns the number rounded as defined by the <code>roundType</code> + /// </summary> + /// <param name="number"> + /// The <see cref="System.Double"/> to round + /// </param> + /// <param name="roundType"> + /// The way in which <code>number</code> should be rounded + /// </param> + /// <returns> + /// The rounded <see cref="System.Double"/> + /// </returns> + public static double Round(double number, RoundType roundType) + { + double val; + + switch (roundType) + { + case RoundType.Up: + val = Math.Ceiling(number); + break; + case RoundType.Down: + val = Math.Floor(number); + break; + case RoundType.Banker: + val = Math.Round(number); + break; + case RoundType.UpToHalf: + val = CeilToHalf(number); + break; + case RoundType.DownToHalf: + val = FloorToHalf(number); + break; + case RoundType.BankerToHalf: + val = RoundToHalf(number); + break; + default: + throw new InvalidOperationException("Unhandled round type: "+roundType); + } + + return val; + } } }