[英]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.