Milan Jayawardane Milan Jayawardane - 5 months ago 10
Java Question

How to print a double with two decimals only when needed

I want to format following values as I described below:

double d = 1234
result should be 1,234

double d = 1234.0
result should be 1,234

double d = 1234.5
result should be 1,234.50

I tried this method

NumberFormat nf = new DecimalFormat("#,##.##");
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(d1));


but it doesn't work when the value is 1234 or 1234 .0

Answer

I like Bathsheba's solution, but if you want 1234.001 to also be viewed as 1234:

NumberFormat nf = new DecimalFormat("#,###.00");
String s = nf.format(d1);
if (s.endsWith(".00")) {
  s = s.substring(0, s.length()-3);
}
Comments