[英]Fixed amount of digits after the decimal
我有許多描述不同對象的double
數字。
例如:
Object A
double a = 10.12
double b = 10.1223
double c = 10.12345
Object B
double a = 10.12
double b = 10.1223
double c = 10.12345
...並且我希望小數點后的位數固定,例如,對象A的小數點后必須具有5(五)位,對象B的小數點后必須具有2(兩位)數並四舍五入。 我想要實現這樣的目標:
Object A
10.12000
10.12230
10.12345
Object B
10.12
10.12
10.12
我嘗試使用setMinimumFractionDigits(5)
或setMinimumFractionDigits(2)
可以工作,但是我有很多對象,並且第一個必須在十進制之后必須有一位數字,其他需要5等。這是一個大項目,並且是面向對象的。
知道如何實現嗎?
請通過創建DecimalFormat
obj來更改代碼,並將其用於格式化Double
對象。
private static DecimalFormat fiveDigitFormat= new DecimalFormat(".#####");
private static DecimalFormat twoDigitFormat= new DecimalFormat(".##");
fiveDigitFormat.format(objA);
twoDigitFormat.format(objB);
就像評論中提到的那樣,簽出DecimalFormat 。
對您來說,它看起來像以下內容:
// For Object A
DecimalFormat dfForObjA = new DecimalFormat("#.#####");
dfForObjA.setRoundingMode(RoundingMode.CEILING);
for (double d : A) { // Assuming A is already declared and initialized
System.out.println(dfForObjA.format(d));
}
// For Object B
DecimalFormat dfForObjB = new DecimalFormat("#.##");
dfForObjB.setRoundingMode(RoundingMode.CEILING);
for (double d : B) { // Assuming B is already declared and initialized
System.out.println(dfForObjB.format(d));
}
注意:對於for每個循環,我不太確定如何使用您的對象來實現它,因為不清楚它們的確切含義或定義方式。
您也可以簡單地使用:
double a = 10.12;
double b = 10.1223;
double c = 10.12345;
System.out.println(String.format("%.5f", a));
System.out.println(String.format("%.5f", b));
System.out.println(String.format("%.2f", c));
它打印:
10.12000
10.12230
10.12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.