How to get the last digit of a big int in PHP

2 Answers

0 votes
function getLastDigitFromString($number) {
    // Ensure the input is a string of digits (not a float or scientific notation)
    if (!preg_match('/^\d+$/', $number)) {
        throw new InvalidArgumentException("Input must be a string of digits.");
    }

    // Return the last character directly
    return substr($number, -1);
}

try {
    $bigInt = "123456789012345678901234567890123"; 
    
    $lastDigit = getLastDigitFromString($bigInt);
    
    echo "The last digit of $bigInt is: $lastDigit\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}




/*
run:

The last digit of 123456789012345678901234567890123 is: 3

*/

 



answered Aug 27, 2025 by avibootz
0 votes
// If you're working with extremely large numbers (beyond PHP_INT_MAX), use number as a string.

// Function to get the last digit of a number
function getLastDigit($number) {
    // Ensure the input is numeric
    if (!is_numeric($number)) {
        throw new InvalidArgumentException("Input must be a numeric value.");
    }

    // Handle negative numbers by taking the absolute value
    $number = abs($number);

    // Get the last digit using the modulus operator
    return $number % 10;
}

try {
    $bigInt = 1234567890123456785; 
    
    $lastDigit = getLastDigit($bigInt);
    
    echo "The last digit of $bigInt is: $lastDigit\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}



/*
run:

The last digit of 1234567890123456785 is: 5

*/

 



answered Aug 27, 2025 by avibootz

Related questions

1 answer 73 views
1 answer 82 views
1 answer 64 views
1 answer 66 views
1 answer 82 views
1 answer 71 views
1 answer 65 views
...