2014-05-14 55 views
0

我是Java新手,一直在通過一本書,我的一個哥們正在讓我借。不過,我相信這本書可能有點過時了。printf in Java SE 8u5 - 打印雙精度到2位小數

我想打印一個價格,這樣做書中使用的例子(packPrice & packVolume都是雙輸入變量使用in.nextDouble()):

double pricePerOunce = packPrice/packVolume; 

System.out.printf("Price per ounce: %8.2f", pricePerOunce); 
System.out.println(); 

然而,當我嘗試在Java SE 8u5(視窗64位)完全相同的代碼,我得到的錯誤:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method printf(String, Object[]) in the type PrintStream is not applicable for   
     the arguments (String, double) 

有誰有補救措施,以我的問題呢?讓我知道是否需要更多信息。

提前致謝!

+0

是否使用一個IDE?如果是這樣,它設置了什麼語言兼容級別?如果它設置爲1.4或更低,則會收到此錯誤消息。 'printf'使用vararg方法,這是直到Java 1.5(也就是Java 5)之前才引入的一個功能。 – yshavit

回答

0

輸出與小數精度的雙的另一種可能的方式是這樣做,

double d = 1.234567; 
DecimalFormat df = new DecimalFormat("#.##"); 
System.out.print(df.format(d)); 

這個例子和類似的問題,可以在這裏找到:set double format with 2 decimal places

相關問題