带前缀空格的双重格式

时间:2018-03-11 10:28:49

标签: java

我想知道,如果有更好的方法,如何在Java中格式化双值。我希望在值之前添加空格,在值之后添加“0”值。

public class Test {
    public static void main(String[] args) {
        double[] a = {1, 10, 100, -1, -10, -100, 1.1, 1.11, -1.1, -1.11, 100123, -123124.1233};
        for (double v : a) {
            System.out.println("[" + formatDouble(v, 15, 10) + "]");
        }
    }

    public static String formatDouble(double value, int prefix, int suffix) {
        String s = String.format("%." + suffix + "f", value);

        String spaces = "";
        for (int i = 0; i < prefix + suffix - s.length(); i++) {
            spaces += " ";
        }

        return spaces + s;
    }
}

输出:

[             1.0000000000]
[            10.0000000000]
[           100.0000000000]
[            -1.0000000000]
[           -10.0000000000]
[          -100.0000000000]
[             1.1000000000]
[             1.1100000000]
[            -1.1000000000]
[            -1.1100000000]
[        100123.0000000000]
[       -123124.1233000000]

如果我使用

 System.out.println("{" + new Formatter().format(Locale.FRANCE, "%+15.10f", v) + "]");

输出将是:

[  +1,0000000000]
[ +10,0000000000]
[+100,0000000000]
[  -1,0000000000]
[ -10,0000000000]
[-100,0000000000]
[  +1,1000000000]
[  +1,1100000000]
[  -1,1000000000]
[  -1,1100000000]
[+100123,0000000000]
[-123124,1233000000]

那不是,我想要的。 我的代码正在运行,但我认为,有更好的解决方案,但我没有找到它。

1 个答案:

答案 0 :(得分:0)

来自Formatter documentation

// Optional locale as the first argument can be used to get // locale-specific formatting of numbers. The precision and width can be // given to round and align the value. formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E); // -> "e = +2,7183"