wood burning stoves 2.0*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 19541
    
  16

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reduce scale of BigDecimal to that required to represent exactly?
 
Similar Threads
Precision problem with Java
Rounding BigDecimal Calculation Yielded Wrong Result
BigDecimal issue
BigDecimal in EL addess scales
java.math.BigDecimal vs double or float datatypes