Domanda

My code looks like:

DecimalFormat df = new DecimalFormat("0.##");
return Double.parseDouble(df.format(sum));

Sum is a double, and when it equals 2, it is returning 2.0. Is this because of how I have my formatting or because of how DecimalFormat is returning a string and I am converting it back to a double?

EDIT: The method I am using requires a double to be returned

È stato utile?

Soluzione

If you were to print out the String returned by df.format(sum), then you would get:

2

Presumably you're printing the double returned by your method, which will always print at least one decimal place:

2.0

The numbers themselves don't have any intrinsic formatting. To control the formatting, use df.format(sum) and print the String. There no need to parse it back to a double, which would intentionally lose the formatting you just applied.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top