Question

Let say:

Math.Round(2.5) //2.0
Math.Round(-2.5) //-2.0
Math.Round(2.5,MidpointRounding.ToEven) // 2.0
Math.Round(2.5,MidpointRounding.AwayFromZero) //3.0

Question: if I change the number with -77777777.5 why the result is -77777778.0 not -77777777.0

Math.Round(-77777777.5) // -77777778.0
Math.Round(-77777777.5,MidpointRounding.AwayFromZero) // -77777778.0
Math.Round(-77777777.5,MidpointRounding.ToEven) // -77777778.0
Was it helpful?

Solution

The default MidPointRounding mode is ToEven. In this mode, as explained by the documentation (where a is the input value),

The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.

-77777777.5 has two nearest integers -77777777 and -77777778 but the latter is the even one so that is the one that is returned.

In the AwayFromZero mode, -77777778 is clearly further from zero than -77777777.

OTHER TIPS

There are two ways of rounding (not specifying MidPointRounding just means that it takes the default option, which is ToEven). The type of rounding determines what happens with 0.5.

Away from zero: like it says, it rounds to the number 'away from the zero' (so to the bigger absolute number). E.g.:

2.5 -> 3
1.5 -> 2
0.5 -> 1
-0.5 -> -1
-1.5 -> -2
-2.5 -> -3

To even: like it says, it rounds to the nearest even number. E.g.:

2.5 -> 2
1.5 -> 2
0.5 -> 0
-0.5 -> 0
-1.5 -> -2
-2.5 -> -2

EDIT: It seems what you want it 'Towards Zero' rounding. As far as I'm aware, that is not an option in C#.

EDIT 2: Since the default C# methods offer no help, you'll have write a custom function. Here you can find an interesting blog about different rounding methods. I have not tested it myself, but this is what is suggested for a towards zero rounding:

public static int RoundToNearestRoundHalfTowardZero(decimal value)
{
    // If value is non-negative, subtract 0.5 and take the next
    // greater integer. If value is negative, add 0.5 and take the
    // next lower integer.
    if (value >= 0)
        return (int)Math.Ceiling(value - 0.5m);
    else
        return (int)Math.Floor(value + 0.5m);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top