2013-02-20 122 views
2

我想在Java中使用printf截斷到第三個小數點,但我一直只得到第二個小數點。下面是代碼,我試圖此行:如何在Java中使用printf截斷?

System.out.printf("The speed in ft/sec is %6.2f\n", time); 
+2

你靠近,用'%6.3f' 看到這也 - http://stackoverflow.com/questions/7197078/printf-f-with-only-2-decimal-要點 – Coffee 2013-02-20 03:25:47

+0

您可能只是在尋找System.out.printf(「速度英尺/秒是%.3f \ n」,時間); – 2013-02-20 03:26:01

回答

5

試試這個:

System.out.printf("The speed in ft/sec is %6.3f\n", time); 

上面會到小數點後三位(不是「截斷」它們)。唯一的區別在於點之後的值。

7

改爲嘗試%6.3f。格式是

%(before).(after)(type) 
    6   3 f 

    6 -> 6 digits before the decimal 
    3 -> 3 digits AFTER the decimal