Search code examples
swiftintdigits

Simpler Way to Get Digit Value From an Integer


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?


Solution

  • 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)