I know how to format a double to keep only the available decimal places (DP), up to a certain number of DPs. This example keeps up to 4 DPs.
double d = 1.0;
DecimalFormat df = new DecimalFormat("#.####");
System.out.print(df.format(d)); // returns "1"
double d = 1.23;
DecimalFormat df = new DecimalFormat("#.####");
System.out.print(df.format(d)); // returns "1.23"
double d = 1.2345678;
DecimalFormat df = new DecimalFormat("#.####");
System.out.print(df.format(d)); // returns "1.2346", rounding off: bad!
Now I want whole numbers e.g. 1.0
to return "1"
without the unnecessary .0
, and the #
format character does provide that functionality. But how do I make sure that the number never gets rounded off? Is there any other way other than an arbitrarily long chain of #
such as "#.###########################################"
?
Or should I just use the default conversion of double to string, and truncate the ".0"
if it appears at the end:
String s = "" + d;
if(s.substring(s.length()-2).equals(".0")) {
s=s.substring(0, s.length()-2);
}
Both ways seems terribly clumsy.