2016-05-04 58 views
1

我試圖回饋社區多一點...打印正確的小數位數? (printf) - JAVA

讓我們說,我的雙變量,有時有不同數量的小數位。 (例如1.2,1.23,1.234)但我只想輸出變量所具有的最小小數位數,最後沒有所有這些0。我怎麼做?

+2

「double x = 2.10」有什麼問題?的System.out.println(X);'? –

+0

或者如果使用'printf()',則使用'%s'而不是'%f'。 – Andreas

+0

我已經擁有了'System.out.printf();'中的所有東西,所以我想保持它的樣子。 :P @ElliottFrisch Plus,這應該有更多的用處,比如將一個字符串繪製到JFrame中,當追加文本時你不能格式化。 – Kaelinator

回答

0

這就是我想出了(它太簡單了,沒有功勞需要):

public static void main(String[] args) { 

    double x = 100.512f; 

    //no decimal places 
    if (x % 1 == 0) { 
    System.out.printf("x = %.0f", (float) x); 
    //one decimal place 
    } else if ((x * 10) % 1 == 0) { 
    System.out.printf("x = %.1f", (float) x); 
    //two decimal places 
    } else if ((x * 100) % 1 == 0) { 
    System.out.printf("x = %.2f", (float) x); 
    //three decimal places 
    } else if ((x * 1000) % 1 == 0) { 
    System.out.printf("x = %.3f", (float) x); 
    } 
    //and so on... 
} 
+0

您將無法成功完成上述任務。例如,對於x = 0.1502,輸出應該是多少?對於x = 0.15002?爲.01500002?爲0.15000000000000002?你如何從x = .05 + .05 + .05中區分出你想要的,因爲它們的內部表示是相同的? – FredK

0

你有雙只使用? BigDecimal可以與縮放比例一起使用,以便它只顯示所需的小數位數。