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

 Accepted Answer

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

More Answers (1)

Jan
Jan on 18 Feb 2011
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 Comment

Thanks, Jan. I didn't know about this syntax.

Sign in to comment.

Categories

Tags

Community Treasure Hunt

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

Start Hunting!