PHP dropping decimals without rounding up

前端 未结 13 2269
独厮守ぢ
独厮守ぢ 2020-12-09 15:09

I want to drop off decimals without rounding up. For example if I have 1.505, I want to drop last decimal and value should be 1.50. Is there such a function in PHP?

13条回答
  •  轮回少年
    2020-12-09 15:50

    Maybe it's too late, but here's a good approach:

        $getTruncatedValue = function( $value, $precision )
        {
            //Casts provided value
            $value = ( string )$value;
    
            //Gets pattern matches
            preg_match( "/(-+)?\d+(\.\d{1,".$precision."})?/" , $value, $matches );
    
            //Returns the full pattern match
            return $matches[0];            
        };
    
        var_dump
        (
            $getTruncatedValue(1.123,1),   //string(3) "1.1"
            $getTruncatedValue(1.345,2),   //string(4) "1.34"
            $getTruncatedValue(1.678,3),   //string(5) "1.678"
            $getTruncatedValue(1.90123,4)  //string(6) "1.9012"  
        );
    
    • The only pitfall in this approach may be the need to use a Regular Expression (which sometimes could bring a performance penalty).

    Note: It's quite hard to find a native approach to truncate decimals, and I think it's not possible to perform that using sprintf and other string-related functions.

提交回复
热议问题