5
1

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.

printf("%02d", "08") でエラー

Last updated at Posted at 2019-07-30

Rubyの printf には次のような仕様があることを知りました。

printf("%02d", "07") # "07"
printf("%02d", "08") # ArgumentError / invalid value for Integer(): "08"

数値を表す書式(この例の"d")があるときに、埋め込まれるものが文字列だった場合は、数値に変換されるというものです。"07" は8進数の7です。"08" は0で始まっているのに8進数の書式としておかしいのでエラーになります。

C、Java、Pythonで試してみたところ、数値の書式に対応するものが文字列のときは必ずエラーになりました。PerlとPHPでは、数値の書式に対応する文字列は10進数として変換されます。

Rubyのソースコードでは、この仕様にあたる部分はsprintf.cの rb_str_format にありました(ver 2.5.2)。

	switch (*p) {
(略)
	  case 'd':
(略)
	    {
		volatile VALUE val = GETARG();
(略)

		switch (TYPE(val)) {
(略)
		  case T_STRING:
		    val = rb_str_to_inum(val, 0, TRUE);
		    goto bin_retry;
5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?