简体   繁体   English

如何在使用DecimalFormat时始终显示小数部分?

[英]How to always show decimal part when using DecimalFormat?

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? 结果应始终格式化为1十进制,如何操作?

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". 基本上,0表示“始终在该位置显示数字”,其中#表示“在该位置显示数字,除非它为零”。

You can read about the patterns here . 您可以在这里阅读有关模式的信息 Change the following line to should do the trick. 改变以下行应该做的伎俩。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM