数字格式化成以0开头的定长字符串

简单写就
String.format("%04d", 3)

不过令我意外的是
StringBuilder +replace 效率居然更高


public class Test {
    public static String  format2(int shortval) {
        String formatted = Integer.toString(shortval);
        StringBuilder buf = new StringBuilder("0000");
        buf.replace(4 - formatted.length(), 4, formatted);
        return buf.toString();
    }

    public static void main(String[] args) {
        String s;
        {
            long start = System.nanoTime();
            int cnt = 100_0000;
            while (cnt-- > 0) {
                s = String.format("%04d", 3);
            }
            long end = System.nanoTime();
            System.out.println(end - start);
        }
        {
            long start = System.nanoTime();
            int cnt = 100_0000;
            while (cnt-- > 0) {
                s = format2((short) 3);
            }
            String a ="";
            long end = System.nanoTime();
            System.out.println(end - start);
        }
    }
}

 

转载于:https://www.cnblogs.com/chenss15060100790/p/11122271.html

你可能感兴趣的:(数字格式化成以0开头的定长字符串)