How do I split a number into individual digits?

% 10 returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.

So if you have the number 10250 as an integer you can get at each number with:

10250 % 10 = 0
(10250 / 10) % 10 = 5
(10250 / 100) % 10 = 2
(10250 / 1000) % 10 = 0
(10250 / 10000) % 10 = 1

So your code could be written as:

num4 = (fm_station / 10) % 10;
num3 = (fm_station / 100) % 10;
num2 = (fm_station / 1000) % 10;
num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.

Tags:

Programming