Tuesday, July 27, 2010

Rounding in C# Explained

In this post I present you 3 basic functions to round numbers in C#.
Like other mathematical functions they are (logically) part of the class Math.

For "standard" rounding there is the function Round(). This expects as the first parameter the number which is to be rounded and as a second optional one the number of decimal places after rounding. If this parameter is not used, 0 is assumed, meaning the number is rounded to the closest integer.

But there are 2 more interesting functions: Ceiling() and Floor().
Both functions round to integers, the first one to the next highest integer and the second on to the next lowest one.

The following example should make this clear:

            decimal d = (decimal)1.5642; // here "1.5642" has to be converted manually with (decimal) to a decimal value, since C# interprets floating numbers as double by standard

            decimal RoundedIntegerNumber = Math.Round(d); // round to integer = 2
            decimal RoundedDecimalNumber = Math.Round(d, 2); // round with 2 decimal places = 1.56

            decimal NextHigherNumber = Math.Ceiling(d); // round to next highest integer = 2
            decimal NextLowerNumber = Math.Floor(d); // round to next lowest integer = 1

No comments:

Post a Comment