Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get length of digits in a number

Tags:

I would like to ask how I can get the length of digits in an Integer. For example:

$num = 245354; $numlength = mb_strlen($num); 

$numlength should be 6 in this example. Somehow I can't manage it to work?

Thanks

EDIT: The example code above --^ and its respective method mb_strlen(); works just fine.

like image 802
supersize Avatar asked Feb 10 '15 14:02

supersize


People also ask

How do you count the number of digits in a number?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do I get the first digit of a number in PHP?

echo substr($mynumber, 0, 2);

Is PHP a digit?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.


2 Answers

Maybe:

$num = 245354; $numlength = strlen((string)$num); 
like image 188
Sergei Gorjunov Avatar answered Sep 22 '22 17:09

Sergei Gorjunov


Accepted answer won't work with the big numbers. The better way to calculate the length of any number is to invoke floor(log10($num) + 1) with a check for 0.

$num = 12357; echo $num !== 0 ? floor(log10($num) + 1) : 1; // prints 5 

It has multiple advantages. It's faster, you don't do the casting of types, it works on big numbers, it works with different number systems like bin, hex, oct.

The equation does the logarithm with base 10 then makes the floor of it and adds 1.

This solution can work independently on the base, so if you want to calculate the length of binary or hex just change the base of the logarithm.

Working fiddle

like image 45
Robert Avatar answered Sep 21 '22 17:09

Robert