Float with PHP precision

Posted on

Coding Problem :

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

Answer :


Answer 1 :

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 .

    


Answer 2 :


Answer 3 :


Answer 4 :


Answer 5 :


Answer 6 :


Answer 7 :


Answer 8 :


Answer 9 :

Leave a Reply

Your email address will not be published. Required fields are marked *