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

9 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Stephen23
Stephen23 el 23 de En. de 2015
Editada: Stephen23 el 23 de En. de 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.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by