Welcome to MSDN Blogs Sign in | Join | Help

SYSK 111: RoundUp and RoundDown in .NET with Decimal Digits

Excel has two very important functions – CEILING and FLOOR that take in two parameters – number and significance.  For example, the CEILING function returns number rounded up to the nearest multiple of significance. For example, if you want to avoid using pennies in your prices and your product is priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the nearest nickel.

 

The System.Math.Ceiling (and correspondingly System.Math.Floor) functions in .NET, however, take only one parameter and return the integer number rounded up or down.

 

The functions below compensate for that lack of functionality natively in .NET and work like Excel’s Ceiling and Floor.

 

Note:  I had to do it for a decimal data type but you can easily convert it to a float, etc.

 

public static decimal RoundUp(decimal n1, decimal n2)

{

    float x1 = System.Convert.ToSingle(n1);

    float x2 = System.Convert.ToSingle(n2);

 

    return System.Convert.ToDecimal(System.Math.Floor((x1 + x2 - 0.00000001) / x2) * x2);

}

 

public static decimal RoundDown(decimal n1, decimal n2)

{

    float x1 = System.Convert.ToSingle(n1);

    float x2 = System.Convert.ToSingle(n2);

 

    return System.Convert.ToDecimal(System.Math.Ceiling((x1 - x2 + 0.00000001) / x2) * x2);

}

 

Published Monday, April 24, 2006 4:41 AM by irenak

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker