eli5: Extracting the Kth digit from a number

295 views

I recently read that this formula,

(Number / 10^K-1) % 10
Edit: updated formula to use K-1

Will give me the Kth digit of Number.

For example if i want the 2nd digit from 345, I have (345/100)%10 which gives 4.

Why does this work? 🤔

In: 3

5 Answers

Anonymous 0 Comments

Pretty sure it’s (Number / 10^K-1 ) % 10

In your example 345/100 = 3.45, and 3.45 % 10 = 3.45 (if you’re working with whole numbers when dividing it’s 3 in both cases.)

You are viewing 1 out of 5 answers, click here to view all answers.