[英]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
一种选择是使用“DecimalFormat.setDecimalSeparatorAlwaysShown”来始终包含小数。
样本:
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.
使用此模式: #0.00
它应该是这样的:
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
扩展十进制格式
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.