How to convert some numbers to strings with the max length?

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'.

 채택된 답변

Image Analyst
Image Analyst 2016년 1월 2일
str = sprintf('%2.2d', yourInteger)

댓글 수: 3

thank you for your answer, but if the length of the number is determined when the program is executed, how to solve it?
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
Thank you very much! That's what I need.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

the cyclist
the cyclist 2016년 1월 2일
An alternative to Image Analyst's (but I prefer his method):
str = num2str(yourInteger,'%02d')

댓글 수: 1

thank you for your answer, but if the length of the number is determined when the program is executed, how to solve it?

댓글을 달려면 로그인하십시오.

Walter Roberson
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).'))

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

질문:

Qiu
2016년 1월 2일

댓글:

Qiu
2016년 1월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by