PHP: get number of decimal digits

前端 未结 18 2277
忘了有多久
忘了有多久 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:13

    I needed a solution that works with various number formats and came up with the following algorithms:

    // Count the number of decimal places
    $current = $value - floor($value);
    for ($decimals = 0; ceil($current); $decimals++) {
        $current = ($value * pow(10, $decimals + 1)) - floor($value * pow(10, $decimals + 1));
    }
    
    // Count the total number of digits (includes decimal places)
    $current = floor($value);
    for ($digits = $decimals; $current; $digits++) {
        $current = floor($current / 10);
    }
    

    Results:

    input:    1
    decimals: 0
    digits:   1
    
    input:    100
    decimals: 0
    digits:   3
    
    input:    0.04
    decimals: 2
    digits:   2
    
    input:    10.004
    decimals: 3
    digits:   5
    
    input:    10.0000001
    decimals: 7
    digits:   9
    
    input:    1.2000000992884E-10
    decimals: 24
    digits:   24
    
    input:    1.2000000992884e6
    decimals: 7
    digits:   14
    

提交回复
热议问题