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?
Multiply by 1. A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.
format(doubleVal); // This ensures no trailing zeroes and no separator if fraction part is 0 (there's a special method setDecimalSeparatorAlwaysShown(false) for that, but it seems to be already disabled by default).
you can round-off the value to 2 digits after decimal, x = floor((x * 100) + 0.5)/100; and then print using printf to truncate any trailing zeros..
If you are willing to switch to BigDecimal
, there is a #stripTrailingZeroes() method that accomplishes this.
You can use String manipulation to remove trailing zeros.
private static String removeTrailingZeros(double d) {
return String.valueOf(d).replaceAll("[0]*$", "").replaceAll(".$", "");
}
System.out.println(removeTrailingZeros(1234.23432400000));
System.out.println(removeTrailingZeros(12.0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With