Search code examples
long-integerdigits

Get the first digit of a Long when not sure how many digits will be in the long


I'm trying to get the first Digit of a Long but the Long i'm getting in from the user will be between 13 - 16 digits long how can I get that first Digit without knowing the exact length


Solution

  • Just format it into a character buffer and get the first one. Only if that becomes a performance bottleneck, come back for a more complex solution.

    In Java:

    // assuming the number is non-negative, 
    // otherwise need to deal with sign
    String firstDigit = String.valueOf(myLong).substring(0,1);