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 Reduce scale of BigDecimal to that required to represent exactly? 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 "Reduce scale of BigDecimal to that required to represent exactly?" Watch "Reduce scale of BigDecimal to that required to represent exactly?" New topic
Author

Reduce scale of BigDecimal to that required to represent exactly?

Xolani Nkosi
Ranch Hand

Joined: Apr 29, 2009
Posts: 32
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
Travis Hein
Ranch Hand

Joined: Jun 06, 2006
Posts: 161
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


Error: Keyboard not attached. Press F1 to continue.
Xolani Nkosi
Ranch Hand

Joined: Apr 29, 2009
Posts: 32
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
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Reduce scale of BigDecimal to that required to represent exactly?
 
Similar Threads
java.math.BigDecimal vs double or float datatypes
BigDecimal issue
Precision problem with Java
Rounding BigDecimal Calculation Yielded Wrong Result
BigDecimal in EL addess scales