Search code examples
javabigdecimal

strip zeros for BigDecimal only for after the decimal point in Java


stripTrailingZeros()

new BigDecimal("4.0000").stripTrailingZeros();
#=> "4" (OK)

new BigDecimal("40.00000").stripTrailingZeros();
#=> "4E+1"

Can I obtain 40 in the second example by using stripTrailingZeros? I mean, I want zero which is after the decimal point to disappear.

Thank you in advance.


Solution

  • stripTrailingZeros() returns a BigDecimal, but you want it to be rendered without zeros, so you want the int version of your BigDecimal:

    System.out.println(new BigDecimal("40.00000").intValue()); // "40"