One DecimalFormatter
isn't going to work for the case of no decimal and the case of two decimal places.
Here's some code that meets all 4 of your conditions:
DecimalFormat formatter1 = new DecimalFormat("0");
DecimalFormat formatter2 = new DecimalFormat("0.00");
double[] input = {0, 1, 1.2, 1.265};
for (int i = 0; i < input.length; i++) {
double test = Math.round(input[i]);
if (Math.abs(test - input[i]) < 1E-6) {
System.out.println(formatter1.format(input[i]));
} else {
System.out.println(formatter2.format(input[i]));
}
}
Edited to add: For jambjo, a version that manipulates the String after the DecimalFormatter
.
DecimalFormat formatter2 = new DecimalFormat("0.00");
double[] input = {0, 1, 1.2, 1.265};
for (int i = 0; i < input.length; i++) {
String result = formatter2.format(input[i]);
int pos = result.indexOf(".00");
if (pos >= 0) {
result = result.substring(0, pos);
}
System.out.println(result);
}