Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java's RoundingMode HALF_UP round -2.5 to -3?

Tags:

java

rounding

RoundingMode allows the programmer to specify in what manner floating point numbers are to be rounded. This is great and all, but there is this one thing about it I found peculiar. Maybe I just misunderstood something fundamental at school.

But this rounding mode is described as the one I was taught at school, "Always round to the nearest number, and when dead in the center, always round up.", but why does it round -2.5 to -3?

I conclude as much that it rounds up in terms of absolute values, but -2 is, to me, certainly "up" from -2.5.

like image 875
Christofer Ohlsson Avatar asked Dec 21 '12 19:12

Christofer Ohlsson


People also ask

What is RoundingMode ceiling?

CEILING. public static final RoundingMode CEILING. Rounding mode to round towards positive infinity. If the result is positive, behaves as for RoundingMode. UP ; if negative, behaves as for RoundingMode.

What is the default rounding of Java?

The default rounding mode of DecimalFormat is RoundingMode. HALF_EVEN . This means that it rounds up, or rounds down if the number is nearer to the next neighbour. When the number is exactly between two neighbours (in your case, 2 and 3), it rounds to the nearest even number (in your case, 2).

Does Java ever round up?

The Java Math class has one more method named “round()” that is also utilized to round up the mathematical values towards their closest integer. This method returns the “integer” type value. To round-up, the “Math. round()” method checks the first decimal value.


2 Answers

RoundingMode.UP is the rounding mode for "away from zero." RoundingMode.FLOOR is towards negative infinity, and CEILING is towards positive infinity. HALF_UP is consistent with UP when the fractional part is exactly 0.5.

They had to choose some term to mean "away from zero."

like image 153
Louis Wasserman Avatar answered Sep 19 '22 22:09

Louis Wasserman


The rationale is outlined in the JavaDocs for RoundingMode.HALF_UP.

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode.UP if the discarded fraction is >= 0.5; otherwise, behaves as for RoundingMode.DOWN. Note that this is the rounding mode commonly taught at school.

The Wikipedia article about Rounding methods makes a different claim:

For example, by this rule the value 23.5 gets rounded to 24, but −23.5 gets rounded to −23.

This is one of two rules generally taught in US elementary mathematics classes.

Though a citation has been requested.

like image 25
Jason Sperske Avatar answered Sep 21 '22 22:09

Jason Sperske