How to create a dynamic format specification for a string variable containing numbers
9 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Stephen23
on 23 Jan 2015
Edited: Stephen23
on 23 Jan 2015
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 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!