view raw
Milan Jayawardane Milan Jayawardane - 11 months ago 34
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("#,##.##");

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


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);