How to get the first x leftmost digits of an integer number in PHP

1 Answer

0 votes
function x_leftmost_digit($n, $x) {
    $x = pow(10, $x);
    while ($n > $x) {
        $n = intval($n / 10);
    }
    
    return $n;
}

srand(time());

for ($i = 1; $i <= 5; $i++) {
    $n = rand(1, 100000);
    $x = rand(1, 5);
    echo $x . " leftmost digit of " . $n . " is " . x_leftmost_digit($n, $x) . PHP_EOL;
}

 
 
/*
run:
 
2 leftmost digit of 1300 is 13
4 leftmost digit of 84680 is 8468
4 leftmost digit of 85552 is 8555
5 leftmost digit of 54087 is 54087
2 leftmost digit of 78053 is 78
 
*/

 



answered Dec 8, 2024 by avibootz
edited Dec 8, 2024 by avibootz

Related questions

...