11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

java 0埋め メモ

Posted at

まとめ

  • Integerは「%02d」で可能。表現しきれない場合は無視
  • Double型の小数点以下の場合は「%.2f」で可能。表現しきれない場合は四捨五入され、無理やり表現

Integer型などでの0埋め

Hoge.java
package hoge;

public class Hoge {
	public static void main(String... args) {
		Integer a = new Integer(1);
		Integer b = new Integer(12);
		Integer c = new Integer(123);
		Integer d = new Integer(1234);
		System.out.println(String.format("%03d", a));
		System.out.println(String.format("%03d", b));
		System.out.println(String.format("%03d", c));
		System.out.println(String.format("%03d", d));
	}
}

実行結果

package hoge;

public class Main {
	public static void main(String... args) {
		Integer a = new Integer(1);
		Integer b = new Integer(12);
		Integer c = new Integer(123);
		Integer d = new Integer(1234);
		System.out.println(String.format("%03d", a));
		System.out.println(String.format("%03d", b));
		System.out.println(String.format("%03d", c));
		System.out.println(String.format("%03d", d));
	}
}

Double型などで小数点以下の0埋め

Hoge.java
package hoge;

public class Hoge {
	public static void main(String... args) {
		Double a = new Double(1);
		Double b = new Double(0.1);
		Double c = new Double(0.12);
		Double d = new Double(12);
		Double e = new Double(12.3);
		Double f = new Double(12.45);
		Double g = new Double(12.456);
		Double h = new Double(12.4547);
		System.out.println(String.format("%.2f", a));
		System.out.println(String.format("%.2f", b));
		System.out.println(String.format("%.2f", c));
		System.out.println(String.format("%.2f", d));
		System.out.println(String.format("%.2f", e));
		System.out.println(String.format("%.2f", f));
		System.out.println(String.format("%.2f", g));
		System.out.println(String.format("%.2f", h));
	}
}

実行結果

注意点:「12.4547」 => 「12.45」として表現されている

1.00
0.10
0.12
12.00
12.30
12.45
12.46
12.45
11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?