How to convert some numbers to strings with the max length?
6 次查看(过去 30 天)
显示 更早的评论
for example, I want to convert 1 to 32 to strings length 2, if shorter, '0's are added to the front of the strings. 1 -> '01', 2 -> '02', ..., 32 -> '32'.
0 个评论
采纳的回答
Image Analyst
2016-1-2
str = sprintf('%2.2d', yourInteger)
3 个评论
Image Analyst
2016-1-3
Is this what you mean?:
% Get a format specifier string for the biggest number we expect to ever have.
yourBiggestInteger = 123456
numDigits = ceil(log10(yourBiggestInteger))
formatSpecifierString = sprintf('%%%d.%dd', numDigits, numDigits)
% Test code:
yourInteger = 12;
str = sprintf(formatSpecifierString, yourInteger)
yourInteger = 1234;
str = sprintf(formatSpecifierString, yourInteger)
In the command window:
yourBiggestInteger =
123456
numDigits =
6
formatSpecifierString =
%6.6d
str =
000012
str =
001234
更多回答(2 个)
the cyclist
2016-1-2
An alternative to Image Analyst's (but I prefer his method):
str = num2str(yourInteger,'%02d')
Walter Roberson
2016-1-4
In the case where you want a bunch of values to all come out the same length, then
cellstr(num2str(TheValues(:)))
You can also toss in an optional format such as
cellstr(num2str(TheValues(:), '%.2f'))
Example:
cellstr(num2str((1:31).'))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!