How can I include leading zeros in a number?

947 views (last 30 days)
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?

Answers (2)

Cedric Wannaz
Cedric Wannaz on 6 Oct 2017
Edited: Cedric Wannaz on 6 Oct 2017
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 =
Jan on 8 May 2018
@RAHUL: The question is not meaningful. There is not object like 00012. If the number 12 is meant, there are no leading zeros. You can add leading zeros only, if you represent 12 as a string. If you display this string, the quotes are not printed. Try it:
n = 12;
fprintf('%06d', n)

Sign in to comment.

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


Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!