Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

MidpointRounding — choosing a rounding rule

MidpointRounding specifies a rounding rule. ToEven and AwayFromZero both choose the nearest result, but resolve values exactly halfway between two possible results differently.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

Math.Round(value, digits, MidpointRounding.ToEven)
Math.Round(value, digits, MidpointRounding.AwayFromZero)

MidpointRounding is an enum in the System namespace, available in .NET 10. Pass it to an overload such as Math.Round(value, digits, mode), where digits is the number of decimal places. This is a library API, not a C# syntax feature requiring LangVersion=preview.

MidpointRounding.ToEven resolves a tie by choosing the result whose last retained digit is even: 2.5m becomes 2, while 3.5m becomes 4 with digits = 0. This is called banker's rounding and is the default for Math.Round overloads without a rounding-mode parameter. MidpointRounding.AwayFromZero resolves a tie by choosing the result farther from zero: 2.5m becomes 3, and -2.5m becomes -3.

Both modes choose the nearest result outside ties: 2.1m becomes 2 in either mode. Thus, AwayFromZero does not always increase the absolute value. At one decimal place, 3.45m is a midpoint, but 3.451m is not. The other modes — ToZero, ToNegativeInfinity, and ToPositiveInfinity — round every value in a specified direction, not just midpoints.

The actual stored value determines the result. The binary representation of double can make an apparent decimal midpoint fall outside a tie. The example uses decimal literals with the m suffix to represent the shown values exactly, and CultureInfo.InvariantCulture to fix the output format.

Examples

using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

Console.WriteLine("value | ToEven | AwayFromZero");
foreach (decimal value in new[] { 2.5m, 3.5m, -2.5m, 2.1m })
{
    decimal even = Math.Round(value, 0, MidpointRounding.ToEven);
    decimal away = Math.Round(value, 0, MidpointRounding.AwayFromZero);
    Console.WriteLine($"{value:F1} | {even:F0} | {away:F0}");
}

Result

value | ToEven | AwayFromZero
2.5 | 2 | 3
3.5 | 4 | 4
-2.5 | -2 | -3
2.1 | 2 | 2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources