• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Rounding using BigDecimal

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic