Java – how to always display decimal parts when using decimal format?

Float sum = new Float(300); // always somehow calculated
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

The result should always be formatted as a decimal number. What should I do?

Solution

change

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

to

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

Basically, 0 means "always show the number in this position", where # means "show the number in this position unless it is zero"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>