Why does NUM2STR ignore the width specifier in MATLAB 7.8 (R2009a)?

4 views (last 30 days)
When I use a format specifier with NUM2STR, it ignores the width specifier. For example the following code returns '1.345' instead of ' 1.345'.
s = num2str(1.345, '%10.3f')

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 14 Jul 2009
This is expected behavior. The documentation of the NUM2STR function states the following:
"num2str removes any leading spaces from the output string."
To work around this issue, use the SPRINTF function instead. Please see the following examples.
% Example 1.
s = sprintf('%10.3f', 1.345)
% Example 2.
y = [1.0 10.0 100.0]
sprintf('%10.2f\n', y)
% Example 3.
a=[1111.111 22.2222 33.33; 444.4 555.55 66.0];
for i=1:2
y=sprintf('%-7.3e \t %-6.4e \t %-5.1e',a(i,1),a(i,2),a(i,3))
end
% Example 4.
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
Which outputs the following:
ans =
314.159265 % Display in fixed-point notation (%f)
314.16 % Display 2 decimal digits (%.2f)
+314.16 % Display + for positive numbers (%+.2f)
314.16 % Set width to 12 characters (%12.2f)
000000314.16 % Replace leading spaces with 0 (%012.2f)

More Answers (0)

Categories

Find more on Simulink Functions in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

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

Start Hunting!