Search code examples
c#decimalroundingcurrencybankers-rounding

Decimal default rounding mode and currency formatting


Consider the following code:

decimal value = 12.345m;
Console.WriteLine(value.ToString("C"));

£12.35

Given that the default MidpointRounding mode in .NET is MidpointRounding.ToEven, why does this value round up (away from an even number, which would be 12.34) when formatting as currency?

For reference:

Console.WriteLine(decimal.Round(value, 2));

12.34


Solution

  • The special currency format specifier C will round away from zero when rounding the decimal places:

    If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.

    You have the fraction digits .345 and the CurrencyDecimalDigits property is set to 2 (in this situation). This means that "right of the number of specified decimal places" is 5, and that is greater or equal to 5. The documentation states that in this case, the value 12.345 is rounded up, away from zero, to 12.35.