PHP - Get length of digits in a number

有些话、适合烂在心里 提交于 2019-11-30 11:08:12

Maybe:

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

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.

More elegant way :)

ceil(log10($num));

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

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.

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!

In PHP types are loosely set and guessed, if you want to see something as a string if it is an integer, float, and (i have not tried this) bool then @Gorjunav is the most correct answer.

Reset the variable as a string

$stringNum = (string) $num;

Then you can go anything string related you want with it! And vice-versa for changing a string to an int

$number = (int) $stringNum;

and so on...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!