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.
Just using some version of
(int)(log($num,10)+1)
fails for 10, 100, 1000, etc. It counts the number 10 as 1 digit, 100 as two digits, etc. It also fails with 0 or any negative number.If you must use math (and the number is non-negative), use:
$numlength = (int)(log($num+1, 10)+1);
Or for a math solution that counts the digits in positive OR negative numbers:
$numlength = ($num>=0) ? (int)(log($num+1, 10)+1) : (int)(log(1-$num, 10)+1);
But the strlen solution is just about as fast in PHP.
More elegant way :)
The following function work for either integers or floats (read comments for more info):
I recommend you using PHP7 one, it's shorter and cleaner.
Hope it helps!
Some math sometime helps. Everything you need is to invoke
floor(log10($num) + 1)
with check for 0.Basically it does the logarithm with base 10 then makes floor of it and adds 1.
Maybe:
You could also use some basic math!