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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3601625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:36:29  来源:igfitidea点击:

How to always show decimal part when using DecimalFormat?

javadecimalformat

提问by Xorty

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 个小数位,怎么办?

回答by GaryF

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 表示“始终显示此位置的数字”,其中 # 表示“显示此位置的数字,除非它为零”。

回答by CoolBeans

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

您可以在此处阅读有关这些模式的信息。将以下行更改为应该可以解决问题。

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