I would like to ask how I can get the length of digits in an Integer. For example:
$num = 245354;
$numlength = mb_strlen($num);
$numl
count only integer value
`<?php
$n1 =12345;
$n2 =123454.55;
$n3 =12345564.557;
echo "The Number you Type: ".$n1."<br>";
$count = 0;
while ($n1 != 0)
{
$n1 = $n1 / 10;
$n1 = intval($n1);
++$count;
}
echo "The Digit in a Number: ".$count;
}
?>`
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
You could also use some basic math!
$digits = (int)(log($num,10)+1)
<?php
$num = 123;
$num2 = 1234;
$num3 = 12345;
function digits($num){
return (int) (log($num, 10) + 1);
}
echo "\n $num: " . digits($num); // 123: 3
echo "\n $num2:" . digits($num2); // 1234: 4
echo "\n $num3:" . digits($num3); // 12345: 5
echo "\n";
More elegant way :)
ceil(log10($num));
The following function work for either integers or floats (read comments for more info):
/* Counts digits of a number, even floats.
* $number: The number.
* $dec: Determines counting digits:
* 0: Without decimal
* 1: Only decimal
* 2: With decimal (i.e. all parts)
*/
// PHP5
function digits_count($number, $dec = 0) {
$number = abs($number);
$numberParts = explode(".", $number);
if (!isset($numberParts[1]))
$numberParts[1] = 0;
return ($dec == 1 ? 0 : strlen($numberParts[0])) +
($dec == 0 ? 0 : strlen($numberParts[1]));
}
// PHP7
function digits_count($number, int $dec = 0) : int {
$number = abs($number);
$numberParts = explode(".", $number);
return ($dec == 1 ? 0 : strlen($numberParts[0])) +
($dec == 0 ? 0 : strlen($numberParts[1] ?? 0));
}
I recommend you using PHP7 one, it's shorter and cleaner.
Hope it helps!
The accepted solution presents a problem when evaluating negative numbers.
It works with a positive number:
$num = 245354;
$numlength = strlen((string)$num);
// Result: 6
But with a negative number, the (-) is added to the count:
$num = -245354;
$numlength = strlen((string)$num);
// Result: 7
Quick workaround:
$num = -245354;
$numlength = strlen((string)abs($num));
// Result: 6