Delete digits after two decimal points, without rounding the value

后端 未结 15 1541
死守一世寂寞
死守一世寂寞 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:42

    A simple function to follow would be "If greater than 0 floor, else ceil", using a multiplier to raise it above the decimal point temporarily whilst doing it:

    function trim_num($num_in, $dec_places = 2) {
        $multiplier = pow(10, $dec_places); // 10, 100, 1000, etc
        if ($num_in > 0) {
            $num_out = floor($num_in * $multiplier) / $multiplier;
        } else {
            $num_out = ceil($num_in * $multiplier) / $multiplier;
        }
        return $num_out;
    }
    

提交回复
热议问题