Get a specific digit of a number from an int in Java

35,266

Modular arithmetic can be used to accomplish what you want. For example, if you divide 123 by 10, and take the remainder, you'd get the first digit 3. If you do integer division of 123 by 100 and then divide the result by 10, you'd get the second digit 2. More generally, the n-th digit of a number can be obtained by the formula (number / base^(n-1)) % base:

public int getNthDigit(int number, int base, int n) {    
  return (int) ((number / Math.pow(base, n - 1)) % base);
}

System.out.println(getNthDigit(123, 10, 1));  // 3
System.out.println(getNthDigit(123, 10, 2));  // 2
System.out.println(getNthDigit(123, 10, 3));  // 1
Share:
35,266
dualCore
Author by

dualCore

I love discovering new programming lauguages, and working with robots!

Updated on February 13, 2020

Comments

  • dualCore
    dualCore over 4 years

    Possible Duplicate:
    Return first digit of an integer

    In my java program, I store a number in an array.

    p1Wins[0] = 123;
    

    How would I check the first digit of p1Wins[0]? Or the second or third? I just need to be able to find the value of any specific digit.

    Thanks!

  • Greg Hewgill
    Greg Hewgill over 12 years
    I don't think you want to use exclusive-or (^) there.
  • zellio
    zellio over 12 years
    @GregHewgill - haha yeah, sorry I prototyped the function in psudeo code and then suddenly couldn't remember the Math.pow function so I had to go look it up.