skip to content

In C#, why does Math.Round(2.5) return 2, and how should an invoicing service round a tax amount to cents?

level: middleimportance: should knowfreq 55%

answer

  1. the default midpoint rule
  2. an enum chooses the rule
  3. is the double really a midpoint
  4. round in decimal with an explicit mode

basics

~20 s

Math.Round uses MidpointRounding.ToEven by default, so a value exactly halfway goes to the even neighbour: 2.5 becomes 2 and 3.5 becomes 4. For cents, round a decimal with Math.Round(amount, 2, mode) and name the mode explicitly.

solid answer

~30 s

Every `Math.Round` overload without a `MidpointRounding` argument uses `MidpointRounding.ToEven`, often called banker's rounding: a value exactly halfway between two candidates goes to the even one, so `Math.Round(2.5)` is `2`, `Math.Round(3.5)` is `4` and `Math.Round(5.125m, 2)` is `5.12`. It avoids the upward bias of always rounding halves up. To round half away from zero, pass the mode: `Math.Round(tax, 2, MidpointRounding.AwayFromZero)`. Round a `decimal`, not a `double`: the double nearest to `0.285` is slightly below it, so even `AwayFromZero` gives `0.28`, while `0.285m` gives `0.29`. The directed modes `ToZero`, `ToNegativeInfinity` and `ToPositiveInfinity` move every non-integral value, not only midpoints.

code

csharp · 15 lines
csharp
Console.WriteLine(Math.Round(2.5));                                    // 2: ToEven by default
Console.WriteLine(Math.Round(3.5));                                    // 4
Console.WriteLine(Math.Round(5.125m, 2));                              // 5.12
Console.WriteLine(Math.Round(5.125m, 2, MidpointRounding.AwayFromZero)); // 5.13

// The double nearest to 0.285 is slightly below it, so it is not a midpoint at all.
Console.WriteLine(Math.Round(0.285, 2, MidpointRounding.AwayFromZero));  // 0.28
Console.WriteLine(Math.Round(0.285m, 2, MidpointRounding.AwayFromZero)); // 0.29

// The directed modes move every non-integral value, not only midpoints.
Console.WriteLine(Math.Round(2.99m, MidpointRounding.ToZero));         // 2
Console.WriteLine(Math.Round(2.01m, MidpointRounding.ToPositiveInfinity)); // 3

Console.WriteLine((int)2.99);                                          // 2: a cast truncates
Console.WriteLine(Convert.ToInt32(2.5));                               // 2: also rounds half to even

go deeper

for a junior

Recall that Math.Round without a mode rounds halves to even, so 2.5 becomes 2, and that a cast to int truncates instead of rounding.

for a middle

Explain the five MidpointRounding members, the difference between midpoint and directed rules, and why a decimal is needed for a true midpoint.

for a senior

Trace a cent discrepancy to a default ToEven, a double that was never a midpoint, or rounding at a different stage, and fix it in one helper.

for a principal

Decide the team's rounding rule and stage with the business, then enforce one helper so invoices, refunds and reports agree.

## The default is round half to even `System.Math` has `Round` overloads for `double` and for `decimal`, with and without a number of fractional digits. Every overload that does not take a `MidpointRounding` argument uses **`MidpointRounding.ToEven`**; the runtime source passes `MidpointRounding.ToEven` explicitly in the two-argument overloads. `decimal.Round` and `Convert.ToInt32(double)` follow the same rule. **ToEven** (banker's rounding) only matters for a value **exactly halfway** between two candidates. Such a value goes to the neighbour whose last digit is even: | Call | Result | |---|---| | `Math.Round(2.5)` | `2` | | `Math.Round(3.5)` | `4` | | `Math.Round(-2.5)` | `-2` | | `Math.Round(5.125m, 2)` | `5.12` | | `Math.Round(5.135m, 2)` | `5.14` | | `Convert.ToInt32(2.5)` | `2` | Why this default? Rounding every half up adds a small upward bias that accumulates over many values. Half to even sends half of the midpoints down and half up, so sums of rounded values stay closer to the sum of the originals. ## The MidpointRounding enum `System.MidpointRounding` has five members, and they come in two kinds: - **Midpoint rules** change only what happens to exact halves: `ToEven` (0, the default) and `AwayFromZero` (1), which rounds 2.5 to 3 and -2.5 to -3, the rule most people learned at school. - **Directed rules** round every non-integral value in one direction: `ToZero` (truncate), `ToNegativeInfinity` (floor) and `ToPositiveInfinity` (ceiling). Despite the enum's name, `Math.Round(2.99m, MidpointRounding.ToZero)` is `2`, and `Math.Round(2.01m, MidpointRounding.ToPositiveInfinity)` is `3`. `Math.Floor`, `Math.Ceiling` and `Math.Truncate` give the same results when rounding to a whole number, and a cast such as `(int)2.99` truncates toward zero. ## A double is rarely a midpoint A midpoint rule only fires when the value being rounded is **exactly** halfway. With `double`, a literal like `0.285` is stored as the nearest binary fraction, 0.28499999999999998…, which is below the midpoint. So: - `Math.Round(0.285, 2, MidpointRounding.AwayFromZero)` returns `0.28`, because there is no midpoint to round away from. - `Math.Round(0.285m, 2, MidpointRounding.AwayFromZero)` returns `0.29`, because the decimal value is exactly 0.285. Other inputs go the other way: `Math.Round(2.675, 2)` returns `2.68` even though the stored double is slightly below 2.675, because the `double` overload scales the value by a power of ten before rounding and the scaled product can itself round onto the midpoint. Which double inputs end up above, below or on the midpoint is hard to predict, so a money path that rounds `double` values to cents gives answers that look random to the person reading the invoice. ## Signatures and limits The overloads to remember are `Math.Round(decimal d, int decimals, MidpointRounding mode)` and `Math.Round(double value, int digits, MidpointRounding mode)`, plus the shorter forms that omit the digits, the mode or both. The digit count has a range: up to 15 for `double` and up to 28 for `decimal`; a larger value throws `ArgumentOutOfRangeException`. The return type matches the input, so `Math.Round(2.5)` is the `double` `2`, and turning it into an `int` still needs a conversion. `Math.Round` never changes the type of the number; it only moves the value to a representable neighbour with fewer digits. ## Rounding tax in an invoicing service 1. Compute in `decimal`: `decimal tax = net * 0.0825m;` produces more places than the currency has. 2. Round with an explicit mode, chosen by the business or the tax rule rather than by the framework default: `Math.Round(tax, 2, MidpointRounding.AwayFromZero)` for half-up, or `MidpointRounding.ToEven` stated out loud if that is the rule. 3. Decide **where** to round: per line, then sum; or sum, then round once. The two can differ by a cent per invoice, so the rule belongs in the specification and in one shared helper. 4. Store the rounded amount, so a later recomputation cannot drift. ## Common traps - Expecting school rounding from `Math.Round(x)` without a mode. - Reading `MidpointRounding.ToZero` as "halves go toward zero"; it truncates every value. - Rounding `double` amounts and blaming the mode when the stored value was never a midpoint. - Converting to an integer with a cast and expecting rounding instead of truncation. Formatting a number with a format string also rounds, under its own rules; that belongs with formatting and culture rather than with `Math.Round`.

  • Why does Math.Round(0.285, 2, MidpointRounding.AwayFromZero) return 0.28 in C#?
    Because the `double` closest to 0.285 is 0.28499999999999998…, slightly below the midpoint, so there is no tie for `AwayFromZero` to break and ordinary rounding goes down. The same call with `0.285m` returns `0.29`, because a `decimal` stores 0.285 exactly. Money should be rounded as `decimal` for that reason.
  • Should an invoice round tax on each line or only on the invoice total?
    Either can be correct; it depends on the tax rule, and the two can differ by a cent or more per invoice. What matters is choosing one, naming the `MidpointRounding` mode explicitly, implementing it in one shared helper, and storing the rounded amounts so totals, refunds and reports recompute the same figures.

  • Math.Round(2.5) returns 3, like school rounding.
  • MidpointRounding.ToZero only changes values that end in exactly 5.
  • AwayFromZero fixes rounding of double amounts to cents.
  • Casting a double to int rounds to the nearest whole number.
  • Banker's rounding is a bug in .NET that should always be overridden.