PHP - Get length of digits in a number

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

    The accepted solution presents a problem when evaluating negative numbers.

    It works with a positive number:

    $num = 245354;
    $numlength = strlen((string)$num);
    // Result: 6
    

    But with a negative number, the (-) is added to the count:

    $num = -245354;
    $numlength = strlen((string)$num);
    // Result: 7
    

    Quick workaround:

    $num = -245354;
    $numlength = strlen((string)abs($num));
    // Result: 6
    

提交回复
热议问题