PHP - Get length of digits in a number

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

提交回复
热议问题