如何在Java的DecimalFormat中强制显示小数点?

huangapple go评论70阅读模式
英文:

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 = &quot;0.##&quot;;
DecimalFormat dc = new DecimalFormat(pattern); // &lt;- &quot;0.##&quot; 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 &#39;DecimalFormat.setDecimalSeparatorAlwaysShown&#39; 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 = &quot;#0.00&quot;;
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(&quot;.&quot;)) {
      return s + &quot;.&quot;;
    }
    return s;
  }
}

huangapple
  • 本文由 发表于 2020年9月18日 01:44:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63943540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定