Java——数字格式化成以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);
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM