This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread 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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Rounding using BigDecimal" Watch "Rounding using BigDecimal" New topic

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.
Joel McNary

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.
I agree. Here's the link:
subject: Rounding using BigDecimal
Similar Threads
regarding bigdecimal.divide problem
Rounding BigDecimal Calculation Yielded Wrong Result
BigDecimal not rounding properly in some cases?
Handling currency throughout an application