combine (0 & 827 & .s) to 0827.s

if i have a input variable x = 827 which is number, and if x is of 3 digit, how can i convert to be of 4 digit like 0827? how can i combine (0 & 827 & .hk) to create a string (0857.hk)?
Thanks very much

 Réponse acceptée

Matt Fig
Matt Fig le 18 Fév 2011

1 vote

x = 827;
S = sprintf('0%i%s\n',x,'.hk')
If your variable x might be any integer between 0 and 9999, and you must have a four digit string before the '.' then you could do:
S = sprintf([repmat('0',1,4-ceil(log10(x))),'%i%s\n'],x,'.hk')

Plus de réponses (1)

Jan
Jan le 18 Fév 2011

2 votes

Easier than the REPMAT approach:
x = 827;
sprintf('%04d.hk', x)
Here the 4 defines the number of digits and the 0 enables leading zeros.

1 commentaire

Matt Fig
Matt Fig le 18 Fév 2011
Thanks, Jan. I didn't know about this syntax.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by