How to number formating with Java in various scenarios:
- if the value is 0,then output will be zero.
- if the value 1,then output will be 1.
- if the value is 1.2,then output will be 1.20.
- if the value is 1.20,then output will be 1.20.
So it means if the input value has decimals then i have to apply numberformat to two decimal places otherwise not required.
-
There's a class for that! http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.htmlWill– Will2012年02月24日 13:40:38 +00:00Commented Feb 24, 2012 at 13:40
-
have you googled? Have you looked decimatFormat? docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.htmlNishant– Nishant2012年02月24日 13:41:27 +00:00Commented Feb 24, 2012 at 13:41
-
How do you get the value, i.e. what Java type?Hauke Ingmar Schmidt– Hauke Ingmar Schmidt2012年02月24日 13:41:56 +00:00Commented Feb 24, 2012 at 13:41
-
stackoverflow.com/questions/264937/… and stackoverflow.com/questions/153724/… should do it.Anton– Anton2012年02月24日 13:44:44 +00:00Commented Feb 24, 2012 at 13:44
2 Answers 2
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);
}
8 Comments
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