5

I have BigDecimal values and I want to have them at least two decimal digits, but I don't want to trim the rest.

So 3 should result in 3.00, but 3.001 should stay 3.001.

I know that I can do this by simply adding 0.00:

new BigDecimal("3").add(new BigDecimal("0.00")) //=> 3.00
new BigDecimal("3.001").add(new BigDecimal("0.00")) //=> 3.001

Is there a build in method or a more elegant way to do this?

I can't use setScale, because I want to keep additional decimals when they exist.

Community
  • 1
  • 1
Alex H
  • 1,424
  • 1
  • 11
  • 25

1 Answers1

8

Actually, you still can use setScale, you just have to check if the current scale if greater than 2 or not:

public static void main(String[] args) {
    BigDecimal bd = new BigDecimal("3.001");

    bd = bd.setScale(Math.max(2, bd.scale()));
    System.out.println(bd);
}

With this code, a BigDecimal that has a scale lower than 2 (like "3") will have its scale set to 2, and if it's not, it will keep its current scale.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Looks good. I hoped for some kind of `setMinScale` but i think it will do. – Alex H Dec 07 '15 at 13:44
  • 1
    @AlexH Yep, it doesn't exist. But do note that there's a short path: if the scale to set is already the current scale, no work is done so the method call is the snippet actually does something only if the scale is less than 2. – Tunaki Dec 07 '15 at 13:49