PHP - Get length of digits in a number

2019-02-12 03:21发布

问题:

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.

回答1:

Maybe:

$num = 245354;
$numlength = strlen((string)$num);


回答2:

Some math sometime helps. Everything you need is to invoke floor(log10($num) + 1) with check for 0.

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

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



回答3:

More elegant way :)

ceil(log10($num));


回答4:

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";


回答5:

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.



回答6:

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!