PHP - Get length of digits in a number

前端 未结 10 1332
长发绾君心
长发绾君心 2021-01-01 12:40

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

相关标签:
10条回答
  • 2021-01-01 13:22

    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.

    0 讨论(0)
  • 2021-01-01 13:22

    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...

    0 讨论(0)
  • 2021-01-01 13:23
    echo strlen((string) abs($num)); // using **abs** it'll work with negative integers as well  
    
    0 讨论(0)
  • 2021-01-01 13:28

    Maybe:

    $num = 245354;
    $numlength = strlen((string)$num);
    
    0 讨论(0)
提交回复
热议问题