2

I need to breakdown a 3 digit number to get each digit's value. I know how to get the first and last digit's values by using the below:

var myInt: Int = 248

print(myInt/100) // first number equals 2
print(myInt%10) // last number equals 8

And I also do know how to get the middle digit's value using the below:

print((myInt - myInt/100*100 - myInt%10)/10) // middle number equals 4

However, I feel that the way I get the middle digit's value is too messy and that there is probably a more simpler way of getting the same result.

Does any know a more simpler option to getting the middle digit's value then what I am currently using?

Jarron
  • 1,049
  • 2
  • 13
  • 29
  • You could also create an *array* with all the decimal digits, compare [Break A Number Up To An Array of Individual Digits](http://stackoverflow.com/questions/32486447/break-a-number-up-to-an-array-of-individual-digits) for various solutions. – Martin R Oct 08 '15 at 08:03

2 Answers2

15

You can generalize the result, but if you just want the middle of 3 digit number:

print((myInt/10)%10)

Dividing by 10 shifts the numbers down one digit. Then the mod 10 gets the last of the shifted digits.

I'll leave generalizing the result to get the nth digit to you, but here are the important details:

% 10 ---> Last digit of a number.
/ 10 ---> Shifts the digits to the right by 1 place (248 -> 24)
Dair
  • 15,910
  • 9
  • 62
  • 107
  • Oh of course, thanks. This is a lot simpler. I'll mark you answer as correct when it lets me. – Jarron Oct 08 '15 at 08:06
0

Convert to String and get characters from this string

FuzzzzyBoy
  • 148
  • 1
  • 13