This week's book giveaway is in the Other Languages forum.We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Reduce scale of BigDecimal to that required to represent exactly?

Xolani Nkosi
Ranch Hand
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
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

Xolani Nkosi
Ranch Hand
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
Posts: 20669
65
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.