[java] 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 = ????

This question is related to java type-conversion

The answer is


Almost certainly more efficient than using Strings:

int firstDigit(int x) {
    while (x > 9) {
        x /= 10;
    }
    return x;
}

(Works only for nonnegative integers.)


int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));

int number = 534;
int firstDigit = number/100; 

( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .

but if you want to get the last number , you can use (%) operator

    int lastDigit = number%10; 

which gives us the reminder of the division , so 534%10 , will yield the number 4 .


int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);

This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.

private static int getMostSignificantDigit(double value) {
    value = Math.abs(value);
    if (value == 0) return 0;
    while (value < 1) value *= 10;
    char firstChar = String.valueOf(value).charAt(0);
    return Integer.parseInt(firstChar + "");
}

To get the first digit, this sticks with String manipulation as it is far easier to read.


firstDigit = number/((int)(pow(10,(int)log(number))));

This should get your first digit using math instead of strings.

In your example log(543) = 2.73 which casted to an int is 2. pow(10, 2) = 100 543/100 = 5.43 but since it's an int it gets truncated to 5


Integer.parseInt will take a string and return a int.


This way might makes more sense if you don't want to use str methods

int first = 1;
for (int i = 10; i < number; i *= 10) {
    first = number / i;
}