Float with PHP precision

5

I am bringing the sum of the values from the database and as a result it returns me according to the example below:

  

6.3285714285714

I would like it to look like this:

  

6.32

I've tried ceil() and round() , but both have returned me more or less. I tried to use substr($valor,0,4); , but the problem is when the value stays:

  

6.328

Remembering that the value may also return:

  

16.3285714285714

And I believe that substr() would not be the solution. How could I solve this?

    
asked by anonymous 25.07.2018 / 22:51

1 answer

5

In fact a truncation function is missing in PHP, they did a in the SO :

function truncate($val, $f = "0") {
    if(($p = strpos($val, '.')) !== false) {
        $val = floatval(substr($val, 0, $p + 1 + $f));
    }
    return $val;
}
echo truncate(6.3285714285714, 2);

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
25.07.2018 / 23:03