multiple digit number in to individual digits
Show older comments
i want to change the number 1123 in 1 1 2 3, want to split combine number into into individual numbers
Accepted Answer
More Answers (3)
John D'Errico
on 22 Jul 2014
N = 1123;
Ndigits = dec2base(N,10) - '0'
Ndigits =
1 1 2 3
3 Comments
Michael Ramage
on 28 Aug 2020
How to do this with a floating point number?
John D'Errico
on 27 Feb 2023
Edited: John D'Errico
on 27 Feb 2023
Not difficult with a floating point number, but remember that a float is NOT an exact decimal representation of that number. But...
X = 1.2345;
dec2base(X*10000,10)
or
dec2base(X*10000,10) - '0'
You can even fuss around and get the decimal point in there if you want, but if you want that, then sprintf is arguably a better choice.
For getting the digits, a conversion to a string is an indirection. Staying at numerical values is usually faster:
N = 1123;
m = floor(log10(N)); % [EDITED] Thanks Stephen
D = mod(floor(N ./ 10 .^ (m:-1:0)), 10);
5 Comments
Almost right, but not quite:
>> N = 10;
>> m = ceil(log10(N));
>> D = mod(floor(N ./ 10 .^ (m-1:-1:0)), 10)
D =
0
It ate my ten!!!!
Using floor not ceil works:
>> N = 10;
>> m = floor(log10(N));
>> D = mod(floor(N ./ 10 .^ (m:-1:0)), 10)
D =
1 0
Jan
on 14 Feb 2017
Thanks, Stephen. I've fixed it. Perhaps I need some holidays.
Adam Danz
on 29 Apr 2020
Quite robust!
Jay Doshi
on 25 Mar 2022
If the number is 0006, and i want all four numbers. What can I do? Because this method just gives me d = 6.
N = 6;
m = 3; % order
d = mod(floor(N ./ 10 .^ (m:-1:0)), 10)
Ramon Villamangca
on 20 Nov 2018
Edited: Ramon Villamangca
on 20 Nov 2018
a simple single line solution:
>> num = 12345042117;
>> arrayfun(@(x) mod(floor(num/10^x),10),floor(log10(num)):-1:0)
ans =
1 2 3 4 5 0 4 2 1 1 7
3 Comments
Jyahway Dong
on 28 Jan 2019
62229893423380308135336276614282806444486645238749
apparently this number above doesn't work for the solutions proposed above, is it simply too long for MatLab to handle?
@Jyahway Dong: read about floating-point numbers and their properties:
For a number with that precision you will need to use the symbolic toolbox, or VPI class, or something similar:
@Jyahway Dong: If the digits are that long, you'll probably input it as a char string, anyway. That means the solution would even be much simpler:
num = '62229893423380308135336276614282806444486645238749';
num - '0'
Categories
Find more on Resizing and Reshaping Matrices 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!