Michoel Michoel - 29 days ago 23
Java Question

Retrieving the first digit of a number

I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.

int number = 534;
String numberString = Integer.toString(number);
char firstLetterChar = numberString.charAt(0);
int firstDigit = ????

Answer
    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
Comments