• 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

Reduce scale of BigDecimal to that required to represent exactly?

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a method in the standard JRE or a commons lib that, given a BigDecimal as input, returns a BigDecimal with the minimum scale required to represent the number exactly?

e.g.

Pass in BigDecimal 1.50000 get back BigDecimal 1.5
Pass in BigDecimal 10.00000 get back BigDecimal 10

Thanks
 
Ranch Hand
Posts: 161
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i believe this is the "setScale() method" with specifying the "ROUND_UNNECESSARY" rounding mode,

the Java API for this: http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html

For example,


which outputs

original: 1.50000 result: 1.5
original: 10.00000 result: 10.0



but this isn't the "two significant digits" thing you have there, in that setScale() works to set the number of decimal places to be scaled to, (typically for currency quantities I would use 2 and ROUND_HALFEVEN)

I guess if you wanted to show up to 1 decimal place, but no decimal places when the number is an integer (whole number), then we could run it through a decimal formatter



which now outputs

original: 1.50000 result: 1.5
original: 10.00000 result: 10

 
Xolani Nkosi
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Doesn't quite do what I want it to - I'd like to be able to pass in a BigDecimal of arbitary scale, and get back one which still represents it exactly, reducing the scale if necessary. So 1.234567890 would only be able to trim it to 1.23456789
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think that one method inside the loop does what you want. I added the toPlainString() to show you how you can print out BigDecimals in a more human readable format.
 
reply
    Bookmark Topic Watch Topic
  • New Topic