Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp
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 Decimal rounding issue

Varun Selva
Ranch Hand
Posts: 48
I have a issue in java rounding

when we are rounding 63.825 to two decimal, what is the answer??
63.82 OR 63.83

63.825
98.975
NumberFormat
63.82
98.98
printf
63.83
98.98
DecimalFormat
63.82
98.98
Math.round
63.83
98.98

Campbell Ritchie
Marshal
Posts: 56599
172
• 1
Mathematically, I would use half‑away‑from‑zero rounding, and get 63.83, 98.98. You will have to look through the API to see what type of rounding those three methods use. I also suggest you print out a BigDecimal…so you can see how close to 8.25 you are actually getting. You cannot represent 0.825 exactly in binary.

I shall move this discussion as not geing a beginner's topic.

Varun Selva
Ranch Hand
Posts: 48
Hi Campbell Ritchie,

result for above code is (new java.math.BigDecimal(63.825))

63.8250000000000028421709430404007434844970703125
98.974999999999994315658113919198513031005859375

How is it coming?

anyway, result should be mathematical answer.. is it???

Greg Charles
Sheriff
Posts: 3015
12
NumberFormat lets you set the rounding mode from the choices in java.math.RoundingMode. The default throughout the Java platform, as far as I know, is half-even rounding. That means 63.825 to two decimal places is 63.82, but 63.855 would be 63.86. That is, if the part you want to round is exactly halfway between the upper bound and lower bounds, then you round in the direction of the even digit. It's meant to prevent introducing cumulative errors in long calculations.

Of course, by that rule, 63.8250000000000028421709430404007434844970703125 should round to 63.83. It seems Java is treating that as exactly 63.825 though. I'm not sure how that works.

Varun Selva
Ranch Hand
Posts: 48
Thanks Greg Charles!
I got some Idea...

Campbell Ritchie
Marshal
Posts: 56599
172
Did you read the API documentation for those four classes? It tells you more about rounding there.