Search code examples
javaformattingbigdecimal

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part


I have a BigDecimal number and i consider only 2 decimal places of it so i truncate it using:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN)

Now I want to print it as String but removing the decimal part if it is 0, for example:

1.00 -> 1

1.50 -> 1.5

1.99 -> 1.99

I tried using a Formatter, formatter.format but i always get the 2 decimal digits.

How can I do this? Maybe working on the string from bd.toPlainString()?


Solution

  • I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

    The code is something like this:

    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    
    DecimalFormat df = new DecimalFormat();
                
    df.setMaximumFractionDigits(2);
                
    df.setMinimumFractionDigits(0);
                
    df.setGroupingUsed(false);
    
    String result = df.format(bd);