Delete digits after two decimal points, without rounding the value

后端 未结 15 1592
死守一世寂寞
死守一世寂寞 2020-11-29 01:04

i have value in php variable like that

$var=\'2.500000550\';
echo $var

what i want is to delete all decimal points after 2 digits.

15条回答
  •  星月不相逢
    2020-11-29 01:54

    floor - not quite! (floor rounds negative numbers)

    A possible solution from cale_b answer.

    static public function rateFloor($rate, $decimals)
    {
    
        $div = "1" . str_repeat("0", $decimals);
    
        if ($rate > 0) {
            return floor($rate * $div) / $div;
        }
    
        $return = floor(abs($rate) * $div) / $div;
    
        return -($return);
    
    }
    

    static public function rateCeil($rate, $decimals)
    {
    
        $div = "1" . str_repeat("0", $decimals);
    
        if ($rate > 0) {
            return ceil($rate * $div) / $div;
        }
    
        $return = ceil(abs($rate) * $div) / $div;
    
        return -($return);
    
    }
    

    Positive

    Rate: 0.00302471

    Floor: 0.00302400

    Ceil: 0.00302500

    Negative

    Rate: -0.00302471

    Floor: -0.00302400

    Ceil: -0.00302500

提交回复
热议问题