Search code examples
javatostringbigdecimal

How to drop insignificant zeros when converting a BigDecimal to a String in Java?


java.math.BigDecimal.toString() can return something like "0.888200000". What can be the best I can do if I want "0.8882" instead? I can never know (unless I calculate it for every particular case) the length of the integer (left to the point) part, the value can be 123.8882 as easily as 123456.88.


Solution

  • Use stripTrailingZeros():

    Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.

    See http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html