Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Rounding using BigDecimal

 
Spencer J Lee
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I'm attempting to round using BigDecimal, but am coming across an unexpected outcome.

gives me the output:

I would have expected the newly scaled BigDecimal value to have the value 93.98 since I specified BigDecimal.ROUND_HALF_UP where BigDecimal.ROUND_HALF_UP is defined as follows in the java docs:
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is >= .5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.

Am I misunderstanding something?
Thanks ahead of time for your suggestions/input.
Spencer
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at this thread.
Your BigDecimal actually has a value of 93.974999999999999431586...etc. (use

instead of bd.doubleValue() to see this result. As such, 93.97 is closer than 93.98; they are not equidistant.
As pointed out in the oter thread, this will work fine if you create you BigDecimal using

or even (for dynamic doubles)


Hope that this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic