How to remove unnecessary trailing zeros from the string representation of a number

Recently I have had an issue where I needed to display some numbers that was sent to an application as strings. A lot of these numbers had some unnecessary trailing zeros at the end. I needed to remove these zeros, but keep the precision of the numbers.

The BigDecimal class came to my help. I converted my strings to BigDecimal instances and I was able to remove the unnecessary zeros and get back a string again the following way:

new BigDecimal("123.45600").stripTrailingZeros().toPlainString()

The result of this is another string, but without the trailing zeros.


This works with any other number, it won’t loose precision, just removes unnecessary zeros.