To get the first digit of a number in Java do this:
Integer.parseInt(String.valueOf(String.valueOf(number).charAt(0)))
.Turn the number to String
, then get the first char
, then turn that char
into a String
, then parse the String
back to a number:
int number = 123;
String numberString = String.valueOf(number); // "123"
char firstCharacter = numberString.charAt(0); // '1'
String firstCharacterString = String.valueOf(firstCharacter); // "1"
int firstDigit = Integer.parseInt(firstCharacterString); // 1