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.
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.
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).
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.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With