「Java」String.format()で数字を桁数指定の0埋め文字列に変換する

説明
public static String format(String format,
Object… args)
パラメータ:
format
書式文字列
args
書式文字列の書式指示子により参照される引数。書式指示子よりも引数が多い場合、余分な引数は無視される。
戻り値:
フォーマットされた文字列

Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class FormatDemo {
public static void main(String[] args) {
String resA, resB, resC, resD, resE, resF;
//数値を3桁の0埋めした文字列に変換。
resA = String.format("%1$03d", 5);
resB = String.format("%1$03d", 60);
resC = String.format("%1$03d", 700);
//数値を4桁の0埋めした文字列に変換。
resD = String.format("%1$04d", 5);
resE = String.format("%1$04d", 60);
resF = String.format("%1$04d", 700);
System.out.println("実行結果:");
System.out.println(resA);
System.out.println(resB);
System.out.println(resC);
System.out.println("*****************");
System.out.println(resD);
System.out.println(resE);
System.out.println(resF);
}
}
package com.arkgame.study; public class FormatDemo { public static void main(String[] args) { String resA, resB, resC, resD, resE, resF; //数値を3桁の0埋めした文字列に変換。 resA = String.format("%1$03d", 5); resB = String.format("%1$03d", 60); resC = String.format("%1$03d", 700); //数値を4桁の0埋めした文字列に変換。 resD = String.format("%1$04d", 5); resE = String.format("%1$04d", 60); resF = String.format("%1$04d", 700); System.out.println("実行結果:"); System.out.println(resA); System.out.println(resB); System.out.println(resC); System.out.println("*****************"); System.out.println(resD); System.out.println(resE); System.out.println(resF); } }
package com.arkgame.study;

public class FormatDemo {

      public static void main(String[] args) {
            String resA, resB, resC, resD, resE, resF;
            //数値を3桁の0埋めした文字列に変換。
            resA = String.format("%1$03d", 5);
            resB = String.format("%1$03d", 60);
            resC = String.format("%1$03d", 700);
            //数値を4桁の0埋めした文字列に変換。
            resD = String.format("%1$04d", 5);
            resE = String.format("%1$04d", 60);
            resF = String.format("%1$04d", 700);

            System.out.println("実行結果:");
            System.out.println(resA);
            System.out.println(resB);
            System.out.println(resC);
            System.out.println("*****************");
            System.out.println(resD);
            System.out.println(resE);
            System.out.println(resF);
      }

}

実行結果:
005
060
700
*****************
0005
0060
0700

Java

Posted by arkgame