2011-11-08 99 views
2

我有內部的一些雙重價值的數組:的Java打印出雙陣列

private double speed[] = {50, 80, 120, 70.3}; 

public void printSpeed() { 
    for(int i = 0; i<=speed.length-1; i++) { 
     System.out.println(speed[i]); 
    } 
} 

output 
50.0 
80.0 
12.0 
70.3 

wanted output 
50 
80 
12 
70.3 

怎麼辦打印陣列的確切字符串?

+0

的System.out.println(速度[1])的toString()代替( 「」」 0" )。? – raven

+0

http://www.dreamincode.net/forums/topic/67144-removing-the-zero-after-the-decimal-point/page__view__findpost__p__434542?s=747a3ccc50326ef03a71c91684c84055 – sathis

回答

11

需要注意的一點是:最終值將會是而不是正好是70.3,因爲這不能完全代表double。如果確切的小數值對您很重要,您應該考慮使用BigDecimal

這聽起來像你想NumberFormat其省略尾隨微不足道的數字:拋開

import java.text.*; 

public class Test { 

    public static void main(String[] args) { 
     // Consider specifying the locale here too 
     NumberFormat nf = new DecimalFormat("0.#"); 

     double[] speeds = { 50, 80, 120, 70.3 }; 
     for (double speed : speeds) { 
      System.out.println(nf.format(speed)); 
     } 
    } 

} 

(作爲一個,我會強烈勸你還是保持[]與類型信息數組聲明 - double[] speeds代替。的double speeds[]它更地道的Java,它把所有類型的信息在一個地方)

1

試試這個:

System.out.println(String.format("%.0f", speed[i])); 
0

請嘗試:

for(int i = 0; i < speed.length; i++) { 
    long l = (long)speed[i]; 
    if(l == speed[i]) { 
     System.out.println(l); 
    } else { 
     System.out.println(speed[i]); 
    } 
}