We all know Math.Round() basically rounds a particular decimal value. But if we look into this method closely it rounds the value to the nearest even value.
For example if we do Math.Round(2.5,0) it will return 2. But we may expect 3 intead of 2. In that case we can use MidPointRounding parameter of
Math.Round() method.
Math.Round can also take a parameter known as MidPointRounding which helps us to select the Rounding option. That means whether we want to round towards even number or to the number away from zero.
For example, when someone do the rounding of 8.5 . MidpointRounding will help to specify whether rounding will be towards the even number (8) or it will be away from zero (9).
The syntax is as follows:
|
Math.Round(doubleValue, precision, MidpointRounding.AwayFromZero)
where
1. doubleValue is the Decimal valuewhich needs to be Rounded.
2. precision is the number of significant decimal places(precision) in the return value.
3. MidPointRounding enumeration value.
MidPointRounding enumeration has two values ToEven and AwayFromZero.
Default value for MidPointRounding is “ToEven”.
ToEven rounds the value to the nearest even number and AwayFromZero rounds the value to the value which is away from zero.
Given below are some examples using both the Rounding options:-
double result;
result = Math.Round(1.5, 0, MidpointRounding.ToEven); // result = 2
result = Math.Round(2.5, 0,MidpointRounding.ToEven); //result = 2
result = Math.Round(-2.5, 0, MidpointRounding.ToEven); //result = -2
result = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // result = 2
result = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // result = 3
result = Math.Round(-2.5, 0, MidpointRounding.AwayFromZero); // result = -3
Note: This is available for .NET Framework version 2.0 and later.
|