Rounding with decimal.Round()

The decimal.Round() method has 4 different overloads:

  1. Accepts just decimal value and rounds it to an integer.
  2. Accepts a decimal value plus an int which is used to round to a certain amount of decimal places.
  3. Accepts a decimal value and an enum that specifies how the rounding should be performed.
  4. Accepts a decimal value, an int which is used to determine the number of decimal places to round to and also an enum that specifies how the rounding should be performed.

The last overload is the one I want to explain as this is where the need to know different strategies for rounding come in.

The first 2 overloads use a strategy of rounding called ‘to even’ or ‘bankers rounding’.

To Even

With this type of rounding strategy the decimal value will be rounded to the appropriate number of decimals and if the proceeding value is a 5 and there are trailing zeroes the preceding value will be rounded to the nearest even number, this essentially means that it could be rounded up or rounded down

e.g. if we had this value 2.345 and we wanted to round the 2 decimal places we would get 2.34 however if we had 2.355 and wanted to perform the same rounding we would get 2.36. Also given the rule about applying it when there are only trailing zeroes if we had 2.34501 unlike the other result we would in fact get 2.35 due to the non trailing zeroes.

The reason this rounding is known as bankers rounding is because it is used a lot in financial calculations to more evenly distribute the rounding results instead of the bias you get with the ‘away from zero’ strategy.

Away from zero

This is the strategy I remember being taught at school and is a simpler strategy that basically means that if your rounding and the proceeding value is a 5 then the preceding value gets rounded away from zero.

e.g. if we had this value 2.345 and we wanted to round the 2 decimal places we would get 2.35 and if we had 2.355 and wanted to perform the same rounding we would get 2.36.

Specifying the rounding strategy

As pointed out before the default is to perform ‘to even’ you can however use the 3rd & 4th overloads to pass in an enum called MidpointRounding this contains 2 values:

  • ToEven
  • AwayFromZero

Further Information

Advertisements