2016-02-01 91 views
1

我有很多描述不同對象的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等,這是大項目,是面向對象的後一個數字。

任何想法我怎麼能做到這一點?

+1

首先請有以下官方文檔的讀取/docs/api/java/text/DecimalFormat.html – Rollerball

回答

1

就像在註釋中,檢查出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)); 
} 

注:對於每一個循環,我也不太清楚如何與你的對象正是實現它,因爲它目前還不清楚他們確切地是或如何定義它們。

2

請更改您的代碼,創建DecimalFormat obj並將其用於格式化Double對象。

private static DecimalFormat fiveDigitFormat= new DecimalFormat(".#####"); 
private static DecimalFormat twoDigitFormat= new DecimalFormat(".##"); 

fiveDigitFormat.format(objA); 
twoDigitFormat.format(objB); 
1

你也可以簡單地使用:

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)); 

它打印:https://docs.oracle.com/javase/7:

10.12000 
10.12230 
10.12