PHP - Get length of digits in a number

前端 未结 10 1330
长发绾君心
长发绾君心 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:18

    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

提交回复
热议问题