What is HALF_EVEN rounding for?

It is useful when you are performing multiple rounding operations and want the cumulative result to be a true average, and not skewed up or down, as it would be with HALF_UP or HALF_DOWN.

Specifically, it is useful for statistical analysis (you don't want the results polluted by a non-random averaging system) or any situation where you want random averaging.


RoundingMode.HALF_EVEN always rounds to the next number, like any other rounding-algorithmn - with only one execption: If the number-to-round is exacly between 2 numbers (2.5, 42.5, -4.5), it will not round it up, but instead round it to the neighbour which is even. Here are some examples:

  • 3.2 -> 3
  • 3.4 -> 3
  • 3.5 -> 4
  • 4.5 -> 4
  • 5.5 -> 6
  • -7.5 -> -8

The behavior is well described in the Javadoc:

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

So given the number 4.5, which falls right in the middle of the range of numbers between 4 and 5, when you call:

BigDecimal value1 = new BigDecimal("4.5").setScale(0, RoundingMode.HALF_EVEN);

The runtime needs to figure out which neighbor to round too, aka, should it round to 4, or to 5? Normally it would round based on which value 4.5 is closer to, but in this case its close to both neighbors. Instead of arbitrarily picking the final result though, it picks the even number. This is the behavior of ROUND_HALF_EVEN. If you wanted to, you could specify ROUND_HALF_UP and the final result would have been 5, and not 4. Also, keep in mind that the determination about how to round is based on what the final result would be (and not on the decimal portion of the big decimal, as you seem to have assumed).


If you have random negative and positive numbers HALF_UP is fine and the net error will tend to 0. HALF_UP is also easier for a human to understand and is often used in finance.

However, if you know you have more of positive (or negative) numbers you will get a bias. HALF_EVEN and HALF_ODD attempts to correct for this by choosing whether to rounding 0.5 up or down based on whether it is more likely to go to an even or odd number. This is statistically fairer, provided you have a 50/50 split of even and odd numbers, however harder for a human to understand.

Tags:

Java

Rounding