PHP: get number of decimal digits

前端 未结 18 2281
忘了有多久
忘了有多久 2020-11-28 09:25

Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using explode)

18条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 10:26

    function numberOfDecimals($value)
    {
        if ((int)$value == $value)
        {
            return 0;
        }
        else if (! is_numeric($value))
        {
            // throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
            return false;
        }
    
        return strlen($value) - strrpos($value, '.') - 1;
    }
    
    
    /* test and proof */
    
    function test($value)
    {
        printf("Testing [%s] : %d decimals\n", $value, numberOfDecimals($value));
    }
    
    foreach(array(1, 1.1, 1.22, 123.456, 0, 1.0, '1.0', 'not a number') as $value)
    {
        test($value);
    }
    

    Outputs:

    Testing [1] : 0 decimals
    Testing [1.1] : 1 decimals
    Testing [1.22] : 2 decimals
    Testing [123.456] : 3 decimals
    Testing [0] : 0 decimals
    Testing [1] : 0 decimals
    Testing [1.0] : 0 decimals
    Testing [not a number] : 0 decimals
    

提交回复
热议问题