Remove trailing zeros from double

Mohit Deshpande picture Mohit Deshpande · Jul 1, 2012 · Viewed 24.8k times · Source

I would like to remove all trailing zeros without truncating or rounding the number if it doesn't have any. For example, the number could be something like 12.0, in which case, the trailing zero should be removed. But the number could also be something almost irrational, like 12.9845927346958762... going on an on to the edge of the screen. Is there a way to setup DecimalFormat or some other class to cut of trailing zeros, while keeping the irrationality intact?

Answer

Keppil picture Keppil · Jul 1, 2012

If you are willing to switch to BigDecimal, there is a #stripTrailingZeroes() method that accomplishes this.