2017-05-03 59 views
0

是否可以在設置小數精度的同一行中設置字段填充的長度?我想要firstPlaceTime顯示3個小數點,如8.250而不是8.25。也許像%8s%3f%8s.3f?謝謝:)同時設置字段填充和小數精度的長度

System.out.format("%-10s%1s%-18s%1s%8s%1s%16s%-10s","Level " + level, "| ", firstPlaceName, "| ", firstPlaceTime + "s ", "|", timeGain + "s ahead |", " " + numberOfRunners + " runners"); 
+2

'firstPlaceTime'已經是一個字符串了嗎?在這種情況下,你需要先將其格式化,然後傳遞給'.format'。如果它是'double'(或'float'),那麼你可以使用'%8.3f'。除此之外:你爲什麼要將格式與String concatenation混合?只需將分隔線和文本放入格式本身即可。 – KevinO

+0

@KevinO'firstPlaceTime'是一個double。我嘗試使用'%8.3f',它會拋出錯誤IllegalFormatConversion。我不熟悉將分隔符和文本添加到格式 –

回答

1

此代碼示出了一個方法來構建的格式字符串以及使用%8.3f以顯示雙。

public static void main(String[] args) 
{ 
    String level = "Beginning"; 
    String firstPlaceName = "TheWinner!"; 
    double firstPlaceTime = 180.234534D; 
    double timeGain = 10.2D; 
    int numberOfRunners = 10; 

    StringBuilder sb = new StringBuilder(); 
    sb.append("Level %-10s"); //the level 
    sb.append("|"); //divider 
    sb.append("%-18s"); //name of winner 
    sb.append("|"); //divider 
    sb.append("%8.3f s "); //winning time 
    sb.append("|"); //divider 
    sb.append("%8.3f s ahead"); //time gain 
    sb.append("|"); //divider 
    sb.append("%5d runners"); // # of runners 

    System.out.format(sb.toString(), 
      level, 
      firstPlaceName, 
      firstPlaceTime, 
      timeGain, 
      numberOfRunners); 

} 

輸出:

Level Beginning |TheWinner!  | 180.235 s | 10.200 s ahead| 10 runners 

編輯:闡述在評論的問題。 OP表示嘗試使用%8.3f並收到格式錯誤。 firstPlaceTime是一個雙。然而,被指定的參數爲:

...,firstPlaceTime + "s ",... 

+ "s "被作爲參數提供,它會被轉換爲String,然後傳遞到.format()。作爲String,它不會是通過%8.3f規範格式化的double。它是建議將文本移動到格式規範中的原因之一,而不是試圖在參數中嘗試各種字符串連接。

+0

這似乎是一個更好的格式,感謝您向我展示它。只是好奇,但爲什麼不'8.3f'工作在我的原始版本的代碼? –

+1

@JoshCorreia,請參閱答案中的詳細說明。但基本上通過指定'firstPlaceTime +'s「',參數變成了'String',不再是雙精度。 – KevinO

+0

啊,這更有意義,謝謝@KevinO –