字符串格式化

在Java中,如何格式化字符串?

以下示例通过使用format()方法中的指定区域设置,格式和参数返回格式化的字符串值。

package com.zaixian;

import java.util.*;

public class StringFormat {
    public static void main(String[] args) {
        double e = Math.E;
        System.out.format("%f%n", e);
        System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
    }
}

执行上面示例代码,得到以下结果 -

2.718282
2,7183

示例2

以下是格式字符串的另一个示例 -

package com.zaixian;

public class StringFormat2 {
    public static void main(String[] args) {
        String name = "Hello World";
        String s1 = String.format("name %s", name);
        String s2 = String.format("value %f", 32.33434);
        String s3 = String.format("value %32.12f", 32.33434);
        System.out.print(s1);
        System.out.print("\n");
        System.out.print(s2);
        System.out.print("\n");
        System.out.print(s3);
        System.out.print("\n");
    }
}

执行上面示例代码,得到以下结果 -

name Hello World
value 32.334340
value                  32.334340000000

上一篇: Java字符串 下一篇: Java数组