Skip to content
Advertisement

Rounding with DecimalFormat in Java

Let’s look at the following statements in Java.

JavaScript

In the above statements, all other cases are obvious except the following.

JavaScript

It should return 3 but it returns 2. How?

Advertisement

Answer

This is intentional behavior. From the documentation:

Rounding

DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting.

About ROUND_HALF_EVEN:

Rounding mode to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it’s even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

This is also known as banker’s rounding.

Math.Round on the other hand uses the following formula, which is “normal” rounding:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement