How to store a number with its leading zeros?

11 views (last 30 days)
I have to input a 9 digit code into 'x' and then separate the digits so I can evaluate some conditions, the thing is, the code can start with a zero. However if I input 'x=012345678' MatLab will say x=12345678. I tried n=num2str(x) but it will say n='12345678' no leading zero. This is really stressing. Is there a way it doesn't skip the zero? I heard you can input a number into a variable as a string, then it wouldn't skip the zero. But I really don't know how to do that (this my first week learning MatLab)

Answers (3)

Stephen23
Stephen23 on 9 Mar 2018
Edited: Stephen23 on 9 Mar 2018
To define x as a character vector:
x = '012345678'
Numeric classes do not store leading zeros, or any formatting information.

Image Analyst
Image Analyst on 10 Mar 2018
Try this:
% Define x as a string with leading zeros.
x = '00012345678'
% Get digits separated:
numbers = x - '0'
You will see
x =
'00012345678'
numbers =
0 0 0 1 2 3 4 5 6 7 8
so your individual digits, including any zeros, are now elements of a numerical vector "numbers" that you can then inspect to "evaluate some conditions".

James Tursa
James Tursa on 10 Mar 2018
Edited: James Tursa on 10 Mar 2018
Another way:
x = your numeric number
the_digits = sprintf('%09d',x)-'0';

Categories

Find more on Entering Commands 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!