-2

I have a float number in PHP : 0.966666666667 I would like to print it like : 0.96 I used round() and number_format() but they give me both 0.97 is there a function to do that please ?

OussamaLord
  • 1,073
  • 5
  • 28
  • 39

2 Answers2

1

You can do this:

$num = 0.966666;
$num = floor($num * 100) / 100;
Niels
  • 48,601
  • 4
  • 62
  • 81
0

The best way to do this I've found is this:

//$val - the value to truncate
//$dist - the number of digits after to decimal place to keep
function truncate($val, $dist) {
    //get position of digit $dist places after decimal point
    $pos = strpos($val,'.');

    if($pos !== false) {//if $val is actually a float

        //get the substring starting at the beginning
        //and ending with the point $dist after the
        //decimal, inclusive -- convert to float.
        $val = floatval(substr($val, 0, $pos + 1 + $dist));

    }          

    return $val;
}

Then just call truncate($YOUR_NUM, 2);.

Source: https://stackoverflow.com/a/12710283/3281590

Community
  • 1
  • 1
Rhitakorrr
  • 104
  • 4