PHP The Longest Digit

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

I want to perform some operation to get the leftmost digit and the remaining remaining digits.

To better explain:

<?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 many ways to do this if you represent a number as a string, but I try not to enter it in a string.

I'm probably looking for a solution that involves bitwise operations, but I'm pretty weak on this topic, so I hope someone who usually works at a low level can answer that!

Thanks a lot.

+6
php digits
source share
7 answers

Avoids the use of any string manipulation, but no guarantees for floating 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); 
+9
source share

I'm sure there is a way to do this without dropping it to a string, but why? The bypass of string so simple:

 $x = (int)substr($num, 0, 1); 

This will give you a good, correct integer.

Obviously, this does not extend the validation of erroneous input and requires $num be a valid number.

+11
source share

Method only for math:

 function leftMost($num) { return floor($num/pow(10,(floor((log10($num)))))); } 

explained, I think ...

1+ log10 from the number calculates the number of digits whose number we use, we use it to remove any decimal values, put it as an exponent, so for a 1-digit number we get 10 ^ 0 = 1 or an 8-digit number we get 10 ^ 8 Then we simply divide 12345678/10000000 = 1.2345678, which gets floor'd and is only 1.

note: this works for numbers between zero and one as well, where it will return 2 to 0.02 and the string conversion will fail.

If you want to work with negative numbers, first do $ num = abs ($ num).

+8
source share

To get the rest of the numbers

$ remainder num = (int) substr ((string) $ num, 1, strlen ($ num));

0
source share

If you select a value for the string, you can use an array type selector.

For example:

 $n = (string)12345676543.876543; echo (int)$n[0]; 
0
source share

@Mark Baker suggested a better solution, although before applying the algorithm you should do abs(floor($num)) .

0
source share

I know that you stated that you want to avoid casting to a string, but if you want to iterate over numbers in PHP, this will be the fastest way:

 $len = strlen($n); for ($i = 0; $i < $len; ++$i) $d = $n[$i]; 

In the fast and dirty benchmark, it was about 50% faster than the equivalent set of mathematical expressions, even while minimizing calls to log and exp .

0
source share

All Articles