同时设置字段填充和小数精度的长度

时间:2017-05-03 23:15:52

标签: java format

是否可以在设置小数精度的同一行中设置字段填充的长度?我希望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");

1 个答案:

答案 0 :(得分:1)

此代码显示了构建格式String以及使用%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,通过double规范进行格式化不会是%8.3f。这是建议将文本移动到格式规范而不是尝试的部分原因 参数中的各种字符串连接。