How to create a dynamic format specification for a string variable containing numbers

9 ビュー (過去 30 日間)
How do I create a dynamic format specification for numbers? I want to create a text string for the title or Tick Labels of a plot. The text string contains a number. The format of the number must be dynamically adapted to the magnitude of the number. I want to do something like text_str=sprintf('The number is %a.bf',n), where n is the number and the format specifiers "a" and "b" are derived from the magnitude of the number.

採用された回答

Stephen23
Stephen23 2015 年 1 月 23 日
編集済み: Stephen23 2015 年 1 月 23 日
According to the sprintf documentation you can use the asterisk * character to control both the field width and precision dynamically:
Field width
Minimum number of characters to print. Can be a number, or an asterisk (*) to refer to an argument in the input list. For example, the input list ('%12d', intmax) is equivalent to ('%*d', 12, intmax).
Precision
...
Can be a number, or an asterisk () to refer to an argument in the input list. For example, the input list ('%6.4f', pi) is equivalent to |('%.*f', 6, 4, pi)|.
If you wish to control something else about the number, such as switching between %f and %e, then you can only do this by supplying a different format string.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by