Delete digits after two decimal points, without rounding the value

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

    Already a lot of possible solutions, I just want to add the one that I came up to solve my problem.

    function truncate_decimals($number, $decimals=2)
    {
      $factor = pow(10,$decimals); 
      $val = intval($number*$factor)/$factor;
      return $val;
    }
    
    
    truncate_decimals(199.9349,2);
    // 199.93
    
    0 讨论(0)
  • 2020-11-29 01:52

    number_format rounds the number

    php > echo number_format(128.20512820513, 2)."\n";
    128.21
    

    I used preg_replace to really cut the string

    php > echo preg_replace('/(\.\d\d).*/', '$1', 128.20512820513)."\n";
    128.20
    
    0 讨论(0)
  • 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

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