2013-03-23 77 views
1

我在Java中收到了大學的作業,我必須使用printf將輸出格式化爲控制檯。這一切都很好,但是由於某種原因,我得到的輸出是10500.000000000002,正確的輸出應該是10500.00。我試圖使用%0.2f,但因爲我的格式爲String,所以我無法做到。Java格式修飾符在字符串中加倍

這是有問題的行:

System.out.printf("\nAge Depreciation Amount:%66s","$"+ ageDepreciationAmount); 

能否請您提出一個方法來正確地格式化呢?請記住這是對java的入門課程,這意味着在編程方面我是一個徹底的災難。

+0

*我是一個完整的災難,當涉及到編程*的xD – Maroun 2013-03-23 16:07:34

回答

1

%0.2f是不正確的。您應該使用%.2f

例子:

System.out.printf("Age Depreciation Amount: %.2f\n", ageDepreciationAmount); 

或者,如果ageDepreciationAmountString

System.out.printf("Age Depreciation Amount: %.2f\n", Double.parseDouble(ageDepreciationAmount)); 

順便說一句,我們通常的printf後添加\n,而不是之前。

輸出:

Age Depreciation Amount: 10500.00 

如果你想以填補空間的輸出,你可以使用%66.2,其中66是總寬度,2是小數位數。但是,這隻適用於數字。

double ageDepreciationAmount = 10500.000000000002; 
    double ageDepreciationAmount2 = 100500.000000000002; 

    String tmp = String.format("$%.2f", ageDepreciationAmount); 
    String tmp2 = String.format("$%.2f", ageDepreciationAmount2); 

    System.out.printf("Age Depreciation Amount: %20s\n", tmp); 
    System.out.printf("Age Depreciation Amount: %20s\n", tmp2); 

輸出:

Age Depreciation Amount:   $10500.00 
Age Depreciation Amount:   $100500.00 
+0

OK,因爲你還需要打印的美元符號,你可以分兩步這樣做謝謝你的工作,但現在我該如何將10500.00移到一定的空間。 在我之前的例子中,它將年齡折舊量66個空格後的輸出移動到右邊,然後輸出美元符號和105000.00。所以它看起來像 年齡折舊金額______________________________ $ 10500.00 – 2013-03-23 21:02:11

+0

@ JohnCarson-Zangor查看更新 – user000001 2013-03-24 03:21:42

+0

非常感謝您的幫助 – 2013-03-24 05:45:39

2
DecimalFormat df = new DecimalFormat("0.##"); 
String result = df.format(10500.000000000002);