zeros before a string using num2str
53 views (last 30 days)
Show older comments
I would like to pad zeros before a string. I have the following code:
a1 = 12.1521;
a2 = 2.1521;
b1 = num2str(a1,'%03.4f');
b2 = num2str(a2,'%03.4f');
The result is b1 = '12.1521';
The result is b2 = '2.1521';
I would like to obtain the result b1 = '012.1521' and b2 = '002.1521'
0 Comments
Accepted Answer
Guillaume
on 19 Oct 2017
Edited: Guillaume
on 19 Oct 2017
The problem with your format string is not the %0 which would work fine, had the next number been correct. The 3 is the problem. In both %3.4f and %03.4f it is ignored as the value is too small. It should always be more than the value after the . since it specifies the minimum total number of characters to print.
Try
num2str(a1, '%08.4f') %8 since you want 4 digits after the . + 1 digit for the . + 3 digit s before
2 Comments
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!