Search code examples
javabigdecimal

BigDecimal with at least two decimals


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.


Solution

  • 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.