How to nicely format floating numbers to string without unnecessary decimal 0's How to nicely format floating numbers to string without unnecessary decimal 0's java java

How to nicely format floating numbers to string without unnecessary decimal 0's


new DecimalFormat("#.##").format(1.199); //"1.2"

As pointed in the comments, this is not the right answer to the original question.
That said, it is a very useful way to format numbers without unnecessary trailing zeros.


If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d){    if(d == (long) d)        return String.format("%d",(long)d);    else        return String.format("%s",d);}

Produces:

2320.1812378751924.5801.2345

And does not rely on string manipulation.