How to always show decimal part when using DecimalFormat?
Asked Answered
I

2

11
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?

Illampu answered 30/8, 2010 at 15:4 Comment(0)
B
38

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".

Bridgework answered 30/8, 2010 at 15:8 Comment(3)
btw if result is 0 and formating is ("#.0") result will be nothing? should I use ("0.0") instead?Illampu
then you will get .0 if the result is 0. If you always want 0.0 then you should change it to ("0.0");Yarak
yes I needed to wait 10 mins since asking or something like that ;)Illampu
Y
7

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

DecimalFormat df = new DecimalFormat("#.0");
Yarak answered 30/8, 2010 at 15:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.