英文:
How to force a decimal point using Java DecimalFormat?
问题
我有这段代码,其中包含两个双精度数:
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat dc = new DecimalFormat(pattern); // <- "0.##" does not work
System.out.println(dc.format(a));
System.out.println(dc.format(b));
需要一个模式,可以产生以下输出:
2000.01
2000.
即使对于 b,小数点也存在,尽管零不会被打印。
英文:
I have this code with two doubles:
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat dc = new DecimalFormat(pattern); // <- "0.##" does not work
System.out.println(dc.format(a));
System.out.println(dc.format(b));
Need to a pattern that would produce the following output:
2000.01
2000.
The decimal point is present for b even though zeros are not printed
答案1
得分: 3
一个选项是使用 'DecimalFormat.setDecimalSeparatorAlwaysShown' 来始终包含小数点。
示例:
```java
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(df.format(a));
System.out.println(df.format(b));
示例输出:
2000.01
2000.
<details>
<summary>英文:</summary>
One option is to use 'DecimalFormat.setDecimalSeparatorAlwaysShown' to always include the decimal.
Sample:
double a = 2000.01;
double b = 2000.00;
String pattern = "0.##";
DecimalFormat df = new DecimalFormat(pattern);
df.setDecimalSeparatorAlwaysShown(true);
System.out.println(df.format(a));
System.out.println(df.format(b));
Sample Output:
2000.01
2000.
</details>
# 答案2
**得分**: 0
```plaintext
使用这个模式:`#0.00`
它应该看起来像这样:
```java
double a = 2000.01;
double b = 2000.00;
String pattern = "#0.00";
DecimalFormat dc = new DecimalFormat(pattern);
System.out.println(dc.format(a));
System.out.println(dc.format(b));
输出结果为:
2000.01
2000.00
英文:
Use this pattern: #0.00
It should look like this:
double a = 2000.01;
double b = 2000.00;
String pattern = "#0.00";
DecimalFormat dc = new DecimalFormat(pattern);
System.out.println(dc.format(a));
System.out.println(dc.format(b));
Which prints:
2000.01
2000.00
答案3
得分: 0
扩展 DecimalFormat
public class MDF extends DecimalFormat {
public String format(double d) {
String s = super.format(d);
if (!s.contains(".")) {
return s + ".";
}
return s;
}
}
英文:
extend DecimalFormat
public class MDF extends DecimalFormat {
public String format(double d) {
String s = super.format(d);
if (!s.contains(".")) {
return s + ".";
}
return s;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论