zeros before a string using num2str

58 ビュー (過去 30 日間)
fdb
fdb 2017 年 10 月 19 日
コメント済み: JG 2021 年 5 月 13 日
I would like to pad zeros before a string. I have the following code:
a1 = 12.1521;
a2 = 2.1521;
b1 = num2str(a1,'%03.4f');
b2 = num2str(a2,'%03.4f');
The result is b1 = '12.1521';
The result is b2 = '2.1521';
I would like to obtain the result b1 = '012.1521' and b2 = '002.1521'

採用された回答

Guillaume
Guillaume 2017 年 10 月 19 日
編集済み: Guillaume 2017 年 10 月 19 日
The problem with your format string is not the %0 which would work fine, had the next number been correct. The 3 is the problem. In both %3.4f and %03.4f it is ignored as the value is too small. It should always be more than the value after the . since it specifies the minimum total number of characters to print.
Try
num2str(a1, '%08.4f') %8 since you want 4 digits after the . + 1 digit for the . + 3 digit s before
  2 件のコメント
JG
JG 2021 年 5 月 13 日
This isn't working for me. Did this behavior change in a later version of MatLab?
JG
JG 2021 年 5 月 13 日
It is working, the 0 before the 8 matters.

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

その他の回答 (2 件)

Adam
Adam 2017 年 10 月 19 日
b = num2str(a,'0%3.4f')
  1 件のコメント
fdb
fdb 2017 年 10 月 19 日
I would like to automatically pad the number of leading zeros, depending on the formatting I specify (in this case 3 digits leading the comma, and 4 digits following the comma). It should also work if I don't know beforehand what the number a1 is.

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


KL
KL 2017 年 10 月 19 日
編集済み: KL 2017 年 10 月 19 日
Try this
A = [69.45 31.71 95.36 3.44 7.82]'
str = string(A)
newStr = pad(str,7,'left','0') %or pad(str,7,'both','0')

カテゴリ

Help Center および 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