Reputation: 15
How to number formating with Java in various scenarios:
So it means if the input value has decimals then i have to apply numberformat to two decimal places otherwise not required.
Upvotes: 1
Views: 328
Reputation: 51445
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);
}
Upvotes: 3
Reputation: 5291
See http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html . An example of such format would be:
double input = 1.2;
DecimalFormat formatter = new DecimalFormat("0.00");
String result = formatter.format(input);
Decimal symbol (as well as other symbols used in the result string) will be dependent on system locale (unless set otherwise) - see http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#setDecimalFormatSymbols%28java.text.DecimalFormatSymbols
Upvotes: -2