フィルターのクリア

How can I include leading zeros in a number?

692 ビュー (過去 30 日間)
Brock Chelle
Brock Chelle 2017 年 10 月 6 日
コメント済み: Stephen23 2024 年 1 月 11 日
I've created a code that requires the user to input a number of their choice. Their number must follow a set of rules, the first being that it must be 6 digits otherwise an error message occurs.
If the user types a number such as 012345, MatLab discards the zero and counts it as a 5 digit number (12345). If I would like MatLab to understand that this is actually a 6-digit number, how would i go about that?

回答 (2 件)

Cedric
Cedric 2017 年 10 月 6 日
編集済み: Cedric 2017 年 10 月 6 日
Store/read the user input as a string.
Or, if you want to bring some flexibility, allow users to enter integers without leading zeros, but then when it becomes important to use/display them with leading zeros, print them on 6 digits with a 0 padding:
n = 12 ; % Stored or entered by user.
n_strPadded = sprintf( '%06d', n ) ;
with that you get:
n_strPadded =
'000012'
  4 件のコメント
Real User
Real User 2024 年 1 月 11 日
Great except that it counts the minus sign as one "zero". Thus, sprintf('%06d', n) works if n>=0 but sprintf('%07d', n) if n<0. Is there any way to say that I want 6 numbers whether n<0 or not?
Stephen23
Stephen23 2024 年 1 月 11 日
"Is there any way to say that I want 6 numbers whether n<0 or not?"
I guess you mean digits, not numbers. Here are two approaches:
n = +4;
sprintf('%0*d',(n<0)+6,n)
ans = '000004'
n = -4;
sprintf('%0*d',(n<0)+6,n)
ans = '-000004'
OR
n = +4;
sprintf('%+07d',n)
ans = '+000004'
n = -4;
sprintf('%+07d',n)
ans = '-000004'

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


Walter Roberson
Walter Roberson 2018 年 5 月 8 日
Use input with the 's' option, and test for length() 6 and that it contains only digits.

カテゴリ

Help Center および File ExchangeString についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by