Search code examples
javabigdecimal

Java BigDecimal : How to fortmat BigDecimal


I'm using BigDecimal for counting some big real number. Although I have try two method : BigDecimal.toString() or BigDecimal.stripTrailingZeros().toString(), it still not sasitfy my requirement.

For example if I use stripTrailingZeros: 4.3000 becomes 4.3 but 4.0 becomes 4.0 not 4. Both above methods cannot sastisty those conditions. So, my question is : how to done it in java ?

Thanks :)


Solution

  • You can use DecimalFormat as follows:

    BigDecimal a = new BigDecimal("4.3000");
    BigDecimal b = new BigDecimal("4.0");
    
    DecimalFormat f = new DecimalFormat("#.#");
    f.setDecimalSeparatorAlwaysShown(false)
    f.setMaximumFractionDigits(340);
    
    System.out.println(f.format(a));
    System.out.println(f.format(b));
    

    which prints

    4.3
    4
    

    As Bhashit pointed out, the default number of fractional digits is 3, but we can set it to the maximum of 340. I actually wasn't aware of this behaviour of DecimalFormat. This means that if you need more than 340 fractional digits, you'll probably have to manipulate the string given by toString() yourself.