views:

55

answers:

2
Float sum = new Float(300); // always somehow calculated
DecimalFormat df = new DecimalFormat("#.#");
String s = df.format(sum/3);  // prints 100, I want 100.0
s = df.format(301/3); // pritns 100.3 which is correct

Result should always be formatted to 1 decimal palce, how to do so?

+4  A: 

You can read about the patterns here. Change the following line to should do the trick.

DecimalFormat df = new DecimalFormat("#.0");
CoolBeans
+2  A: 

Change

DecimalFormat df = new DecimalFormat("#.#");

to

DecimalFormat df = new DecimalFormat("#.0");

Basically, a 0 means "always show the digit in this position", where a # means "show the digit in this position unless it's zero".

GaryF
thanx, worked and I understand now ...
Xorty
btw if result is 0 and formating is ("#.0") result will be nothing? should I use ("0.0") instead?
Xorty
then you will get .0 if the result is 0. If you always want 0.0 then you should change it to ("0.0");
CoolBeans
nice, got it ...
Xorty
You are welcome. Please accept an answer if you could.
CoolBeans
yes I needed to wait 10 mins since asking or something like that ;)
Xorty