Reputation: 997
I have this code with two doubles:
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat dc = new DecimalFormat(pattern); // <- "0.##" does not work
System.out.println(dc.format(a));
System.out.println(dc.format(b));
Need to a pattern that would produce the following output:
2000.01
2000.
The decimal point is present for b even though zeros are not printed
Upvotes: 0
Views: 824
Reputation: 666
One option is to use 'DecimalFormat.setDecimalSeparatorAlwaysShown' to always include the decimal.
Sample:
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(df.format(a));
System.out.println(df.format(b));
Sample Output:
2000.01
2000.
Upvotes: 3
Reputation: 35011
extend DecimalFormat
public class MDF extends DecimalFormat {
public String format(double d) {
String s = super.format(d);
if (!s.contains(".")) {
return s + ".";
}
return s;
}
}
Upvotes: 0
Reputation: 31987
Use this pattern: #0.00
It should look like this:
double a = 2000.01;
double b = 2000.00;
String pattern = "#0.00";
DecimalFormat dc = new DecimalFormat(pattern);
System.out.println(dc.format(a));
System.out.println(dc.format(b));
Which prints:
2000.01
2000.00
Upvotes: 0