PHP: get number of decimal digits

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

    Here's a function that takes into account trailing zeroes:

    function get_precision($value) {
        if (!is_numeric($value)) { return false; }
        $decimal = $value - floor($value); //get the decimal portion of the number
        if ($decimal == 0) { return 0; } //if it's a whole number
        $precision = strlen($decimal) - 2; //-2 to account for "0."
        return $precision; 
    }
    

提交回复
热议问题