This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Rounding using BigDecimal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Rounding using BigDecimal" Watch "Rounding using BigDecimal" New topic
Author

Rounding using BigDecimal

Spencer J Lee
Ranch Hand

Joined: Mar 19, 2003
Posts: 30
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

Joined: Aug 20, 2001
Posts: 1817

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Rounding using BigDecimal