2013-09-16 38 views
2

我有一個雙精度數字{1.0,2.3,3.45,7.8,9.0,5.0}的數組。在輸出數字時,我想讓那些十進制數爲0的數字顯示爲一個整數:例如,1.0 => 1,9.0 => 9.Java:如果將雙精度型數字輸出爲整數格式(如果它的小數點爲0)

在java中,您如何輕鬆做到這一點?感謝

+2

查找'NumberFormat'類。 –

+1

'DecimalFormat'或如果它的控制檯'System.printf()'就像在c – nachokk

+0

http://stackoverflow.com/questions/2683324/java-char-array-to-int嘗試鏈接到一個問題之前問 –

回答

4

不使用我建議任何庫:

public static String parse(double num) { 
    if((int) num == num) return Integer.toString((int) num); //for you, StackOverflowException 
    return String.valueOf(num); //and for you, Christian Kuetbach 
} 

鑄造雙爲int將切斷小數。

隨意將數字轉換爲任何您喜歡的方式的字符串;)

+0

您可否使用[Integer.toString](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int))?在我看來這是比「」+任何東西都更好的風格... – tilpner

+0

我會使用String.valueOf():) –

+0

或者那一個,但String.valueOf在內部調用Integer.toString,所以它是一個方法調用較少。不值得擔心,但... – tilpner

相關問題