Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Decimal rounding issue  RSS feed

 
Varun Selva
Ranch Hand
Posts: 48
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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





Answer :

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
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Campbell Ritchie,
Thanks for your response.

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
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Greg Charles!
I got some Idea...
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you read the API documentation for those four classes? It tells you more about rounding there.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!