PHP dropping decimals without rounding up

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

    The answers of RenaPot, IsisCode, goredwards are not correct.

    Because of how float works in computers (in general), float is not accurate.

    To replicate the issue:

    floor(19.99 * 100);  // Outputs 1998 instead of 1999
    floor( 5.10 * 100);  // Outputs  509 instead of  510
    

    Within PHP internally, 19.99 * 100 results in something like 1998.999999999999999, which when we do floor of that, we get 1998.

    Solution:

    Solution 1: Use bcmath library (Suggested by @SamyMassoud) if you have it installed (some shared hosting servers may not have it installed by default). Like so:

    //floor(19.99 * 100);// Original
    floor(bcmul(19.99, 100));// Outputs 1999
    

    Solution 2: String manipulation (my recommendation):

    // Works with positive and negative numbers, and integers and floats and strings
    function withoutRounding($number, $total_decimals) {
        $number = (string)$number;
        if($number === '') {
            $number = '0';
        }
        if(strpos($number, '.') === false) {
            $number .= '.';
        }
        $number_arr = explode('.', $number);
    
        $decimals = substr($number_arr[1], 0, $total_decimals);
        if($decimals === false) {
            $decimals = '0';
        }
    
        $return = '';
        if($total_decimals == 0) {
            $return = $number_arr[0];
        } else {
            if(strlen($decimals) < $total_decimals) {
                $decimals = str_pad($decimals, $total_decimals, '0', STR_PAD_RIGHT);
            }
            $return = $number_arr[0] . '.' . $decimals;
        }
        return $return;
    }
    
    // How to use:
    withoutRounding(19.99, 2);// Return "19.99"
    withoutRounding(1.505, 2);// Return "1.50"
    withoutRounding(5.1, 2);// Return "5.10"
    

提交回复
热议问题