0
0

More than 3 years have passed since last update.

perlなどのsprintf()で整数のゼロ埋めと少数の有効数字の設定を同時にしたい

Last updated at Posted at 2020-01-07

実現したいこと

3.5を003.500のように設定したい

# 答え
my $text = sprintf("%07.3f", 3.5); # -> 003.500となる

1. 整数のゼロ埋め

例)3を003のようにゼロ埋めしたい

my $text = sprintf("%03d", 3);

2. 少数の有効数字の設定

例)3.5を3.500のようにしたい

my $text = sprintf("%.3f", 3.5);

3. 1と2を組み合わせたい

例)3.5を003.500のように表現したい
以下のように1と2の書式を単純に組み合わせた場合、意図した形式にならない。

# 意図した形式にならない例
my $text = sprintf("%03.3f\n", 3.5); # -> 3.500となる

以下のように設定することで意図した形式になる。

# 意図した形式になる例
my $text = sprintf("%07.3f", 3.5); # -> 003.500となる

少数以下の桁数 + コンマの数(1個)+ ゼロ埋め対象の桁数を%.の間に記入する。
例では、3+1+3=7なので07と記入する。


参考

https://stackoverflow.com/questions/28739818/php-how-to-add-leading-zeros-zero-padding-to-float-via-sprintf

0
0
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
0
0