Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

MidpointRounding.AwayFromZero with decimal.Round

Choose an explicit tie rule: round to the nearest value, but at an exact midpoint choose the result with the larger absolute value.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

public static decimal Round(decimal d, int decimals, System.MidpointRounding mode);
public static decimal Round(decimal d, System.MidpointRounding mode);

// Call with an explicit midpoint rule:
decimal rounded = decimal.Round(2.25m, 1, System.MidpointRounding.AwayFromZero);

With C# 12 and .NET 8, decimal.Round(d, decimals, MidpointRounding.AwayFromZero) returns a decimal, the C# alias for System.Decimal. AwayFromZero is a member of the System.MidpointRounding enum and is passed as the static method’s mode argument. The m suffix makes a literal a decimal, not a double.

The method picks the nearest value at the requested decimal place. Only at an exact tie does AwayFromZero pick the candidate with the larger absolute value: to one place, 2.25m becomes 2.3m and -2.25m becomes -2.3m. Off the midpoint, 2.24m becomes 2.2m. The default ToEven rule in decimal.Round(d, decimals) breaks ties by choosing the result whose last retained digit is even. By contrast, the directed mode ToZero rounds toward zero even for non-midpoints.

decimals counts places after the decimal separator, from 0 to 28 inclusive. decimal.Round(d, mode) rounds to a whole number but still returns a decimal. In the three-argument overload, an out-of-range decimals throws ArgumentOutOfRangeException, and an undefined mode throws ArgumentException.

Examples

using System;
using System.Globalization;

decimal[] values = [2.25m, -2.25m, 2.24m, 2.26m];

Console.WriteLine("Input | Default | AwayFromZero");
foreach (decimal value in values)
{
    decimal defaultResult = decimal.Round(value, 1);
    decimal explicitResult = decimal.Round(value, 1, MidpointRounding.AwayFromZero);
    Console.WriteLine(string.Create(CultureInfo.InvariantCulture,
        $"{value:F2} | {defaultResult:F1} | {explicitResult:F1}"));
}

Result

Input | Default | AwayFromZero
2.25 | 2.2 | 2.3
-2.25 | -2.2 | -2.3
2.24 | 2.2 | 2.2
2.26 | 2.3 | 2.3

Compare the columns: the modes differ only in the two exact-midpoint rows. `CultureInfo.InvariantCulture` keeps the decimal point in the output.

Related lessons

  • C# · Lesson 7 · Advanced · Version: 3

Sources