PHP dropping decimals without rounding up

前端 未结 13 2163
独厮守ぢ
独厮守ぢ 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:57

    I know this is a late answer but here is a simple solution. Using the OP example of 1.505 you can simply use the following to get to 1.50.

    function truncateExtraDecimals($val, $precision) {
        $pow = pow(10, $precision);
        $precise = (int)($val * $pow);
        return (float)($precise / $pow); 
    }
    

    This manages both positive and negative values without the concern to filter which function to use and lends to correct results without the worry about what other functions might do with the value.

    $val = 1.509;
    $truncated = sprintf('%.2f', truncateExtraDecimals($val, 2));
    echo "Result: {$truncated}";
    
    Result: 1.50
    

    The sprintf is needed to get exactly 2 decimals to display otherwise the Result would have been 1.5 instead of 1.50.

    0 讨论(0)
提交回复
热议问题