Search code examples
phpdigits

PHP Leftmost digit


let's say I have a variable containing an integer or a float (since integers might overflow into a float in PHP).

I want to run some operation to get the leftmost digit and the rest of the remaining digits.

To explain better:

<?php

$x   = NULL;  //this will hold first digit
$num = 12345; //int

/// run operation


//outputs
//$x   = 1;
//$num = 2345;
var_dump($x, $num);

?>

Now, I know there's multitudes of ways to do this if you represent the number as a string, but I'm trying to avoid type casting it into a string.

I'm probably looking for a solution which includes bitwise operations, but I'm pretty weak in that topic so I'm hoping someone who usually works low-level might be able to answer this!

Thanks a bunch.


Solution

  • Avoids using any string manipulation, but no guarantees for float or even negative values

    $x   = NULL;  //this will hold first digit
    $num = 12345; //int
    
    $m = 1;
    while(true) {
        $m *= 10;
        if ($m > $num)
            break;
    }
    
    $m /= 10;
    
    $x = (int) floor($num / $m);
    $num = $num % $m;
    
    
    //outputs
    //$x   = 1;
    //$num = 2345;
    var_dump($x, $num);