The Java library has a built-in class that can do this for it. It's BigDecimal.
Here is an example usage:
BigDecimal number = new BigDecimal("10.2270");
System.out.println(number.stripTrailingZeros().toPlainString());
Output:
10.227
Note: It is important to use the BigDecimal constructor that takes a String. You probably don't want the one that takes a double.
Here's a method that will take a Collection<String> and return another Collection<String> of numbers with trailing zeros removed, gift wrapped.
public static Collection<String> stripZeros(Collection<String> numbers) {
if (numbers == null) {
throw new NullPointerException("numbers is null");
}
ArrayList<String> value = new ArrayList<>();
for (String number : numbers) {
value.add(new BigDecimal(number).stripTrailingZeros().toPlainString());
}
return Collections.unmodifiableList(value);
}
Example usage:
ArrayList<String> input = new ArrayList<String>() {{
add("10.0"); add("10.00"); add("10.10"); add("10.2270");
}};
Collection<String> output = stripZeros(input);
System.out.println(output);
Outputs:
[10, 10, 10.1, 10.227]
doubleas the input. This question has aString.String string1 = Double.valueOf(a).toString()