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

 採用された回答

Matt Fig
Matt Fig 2011 年 2 月 18 日

1 投票

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

1 件のコメント

Hello Blower
Hello Blower 2011 年 2 月 18 日
thanks a lot

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2011 年 2 月 18 日

2 投票

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 件のコメント

Matt Fig
Matt Fig 2011 年 2 月 18 日
Thanks, Jan. I didn't know about this syntax.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by