programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# java.math.RoundingMode.HALF_UP functionality

Ryan McClain
Ranch Hand
Posts: 153
1

The Java API of java.math.RoundingMode.HALF_UP states:
"Round towards the "nearest neighbor" unless both neighbors are equidistant, in which case round up."

I am trying to understand what 'equidistant' means in the case of a 2 decimal points precision:

What if you are rounding up a double value to 0.00 precision? What is the nearest neighbor then?
e.g.: For 0.495, I assume the nearest neighbors are 0.50 and 0.490. Are these neighbors equidistant from 0.495?

source: Murach's Java SE 6, page 115, pdf page 135

Campbell Ritchie
Marshal
Posts: 56600
172
In two decimal points' precision 1.00 and 2.00 are equidistant from 1.50.

Campbell Ritchie
Marshal
Posts: 56600
172
No, I was mistaken
1.235 is equidistant from 1.23 and 1.24.

Ryan McClain
Ranch Hand
Posts: 153
1
Then, according to the API 1.235 should round up to 1.24?

Campbell Ritchie
Marshal
Posts: 56600
172
Yes. That is the same as I learnt at school aged about 12. If you look at the tables in the RoundingMode enum documentation, you find what I think are two inaccuracies.
• 1: UP seems to mean away from zero since −2.5 → −3.
• 2: It says that is the rounding mode commonly taught at school. That is correct (I think) for English‑speaking countries but I have seen school Maths books from elsewhere teaching the equivalent of ROUND_HALF_EVEN.
• Note that UP both in BigDecimal and in RoundingMode both say away from zero.

Ryan McClain
Ranch Hand
Posts: 153
1
Yes, it goes without saying I've also seen that classic rounding method at early age at school.
Well, I understand this HALF_UP now.