Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reduce scale of BigDecimal to that required to represent exactly?

 
Xolani Nkosi
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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
 
Travis Hein
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Rob Spoor
Sheriff
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic