Remove trailing zero in Java

Use DecimalFormat, its cleanest way

String s = "10.1200";
DecimalFormat decimalFormat = new DecimalFormat("0.#####");
String result = decimalFormat.format(Double.valueOf(s));
System.out.println(result);

String value = "10.010"
String s = new DecimalFormat("0.####").format(Double.parseDouble(value));
System.out.println(s);

Output:

   10.01

Kent's string manipulation answer magically works and also caters for precision loss, But here's a cleaner solution using BigDecimal

String value = "10.234000";
BigDecimal stripedVal = new BigDecimal(value).stripTrailingZeros();

You can then convert to other types

String stringValue = stripedVal.toPlainString();
double doubleValue = stripedVal.doubleValue();
long longValue = stripedVal.longValue();

If precision loss is an ultimate concern for you, then obtain the exact primitive value. This would throw ArithmeticException if there'll be any precision loss for the primitive. See below

int intValue = stripedVal.intValueExact();

there are possibilities:

1000    -> 1000
10.000  -> 10 (without point in result)
10.0100 -> 10.01 
10.1234 -> 10.1234

I am lazy and stupid, just

s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");

Same solution using contains instead of indexOf as mentioned in some of the comments for easy understanding

 s = s.contains(".") ? s.replaceAll("0*$","").replaceAll("\\.$","") : s

Tags:

Java

String

Regex