PHP dropping decimals without rounding up

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

    To do this accurately for both +ve and -ve numbers you need use:
    - the php floor() function for +ve numbers
    - the php ceil() function for -ve numbers

    function truncate_float($number, $decimals) {
        $power = pow(10, $decimals); 
        if($number > 0){
            return floor($number * $power) / $power; 
        } else {
            return ceil($number * $power) / $power; 
        }
    }
    

    the reason for this is that floor() always rounds the number down, not towards zero.
    ie floor() effectively rounds -ve numbers towards a larger absolute value
    eg floor(1.5) = 1 while floor(-1.5) = -2

    Therefore, for the multiply by power, remove decimals, divide by power truncate method :
    - floor() only works for positive numbers
    - ceil() only works for negative numbers

    To test this, copy the following code into the editor of http://phpfiddle.org/lite (or similar):

    Php Truncate Function

    0){ return floor($number * $power) / $power; } else { return ceil($number * $power) / $power; } } // demo $lat = 52.4884; $lng = -1.88651; $lat_tr = truncate_float($lat, 3); $lng_tr = truncate_float($lng, 3); echo 'lat = ' . $lat . '
    '; echo 'lat truncated = ' . $lat_tr . '
    '; echo 'lat = ' . $lng . '
    '; echo 'lat truncated = ' . $lng_tr . '

    '; // demo of floor() on negatives echo 'floor (1.5) = ' . floor(1.5) . '
    '; echo 'floor (-1.5) = ' . floor(-1.5) . '
    '; ?>

提交回复
热议问题