Let’s look at the following statements in Java.
System.out.println(new DecimalFormat("0").format(2.4)); //returns 2
System.out.println(new DecimalFormat("0").format(2.5)); //returns 2 <---Concentrate here
System.out.println(Math.round(2.5)); //returns 3
System.out.println(new DecimalFormat("0").format(2.6)); //returns 3
System.out.println(new DecimalFormat("0").format(3.5)); //returns 4
In the above statements, all other cases are obvious except the following.
System.out.println(new DecimalFormat("0").format(2.5));
It should return 3 but it returns 2. How?
This is intentional behavior. From the documentation:
About ROUND_HALF_EVEN:
This is also known as banker’s rounding.
Math.Roundon the other hand uses the following formula, which is "normal" rounding: