简体   繁体   English

如何使用 Java DecimalFormat 强制使用小数点?

[英]How to force a decimal point using Java DecimalFormat?

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即使不打印零,也存在小数点b

One option is to use 'DecimalFormat.setDecimalSeparatorAlwaysShown' to always include the decimal.一种选择是使用“DecimalFormat.setDecimalSeparatorAlwaysShown”来始终包含小数。

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.

Use this pattern: #0.00使用此模式: #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

extend DecimalFormat扩展十进制格式

public class MDF extends DecimalFormat {
  public String format(double d) {
    String s = super.format(d);
    if (!s.contains(".")) {
      return s + ".";
    }
    return s;
  }
}

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

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