Padding flag of the formatting operator in compose()

1 回表示 (過去 30 日間)
Cristian Berceanu
Cristian Berceanu 2023 年 10 月 31 日
コメント済み: Dyuman Joshi 2023 年 11 月 1 日
I am trying to get my head around to how the padding flag works. For instance, I get:
>> compose("%05d",45)
ans =
"00045"
Nevertheless, if I try the same using a formatting operator for floating number, this flag seems to do nothing:
>> compose("%05.2f",45.23)
ans =
"45.23"
Why is the result not "00045.23" in this case?
Regards,
Cristian

採用された回答

Matt J
Matt J 2023 年 10 月 31 日
Because then the length of the string would be 8 instead of 5.
compose("%08.2f",45.23)
ans = "00045.23"

その他の回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2023 年 10 月 31 日
編集済み: Dyuman Joshi 2023 年 10 月 31 日
The number before the decimal specifies the length/field width of the output string.
Padding will only be there if there is space for it.
sprintf('%0*.2f\n', [6 45.23 7 45.23 8 45.23])
ans =
'045.23 0045.23 00045.23 '
sprintf('%0*.3f\n', [7 123.456 8 123.456 9 123.456])
ans =
'123.456 0123.456 00123.456 '
  2 件のコメント
Adam Danz
Adam Danz 2023 年 11 月 1 日
Ha! I don't think I've seen this use of sprintf before. It took me a few minutes to figure out that the odd index values of the 2nd argument are space indicators and the even index values the values to be printed. Difficult to read but interesting! Ya learn something new every day! :)
Dyuman Joshi
Dyuman Joshi 2023 年 11 月 1 日
It is an interesting funcitonality!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by