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 ?
Asked
Active
Viewed 773 times
-2

OussamaLord
- 1,073
- 5
- 28
- 39
-
3Please research prior to asking: http://stackoverflow.com/questions/4668628/truncate-float-numbers-with-php – Alex Jurado - Bitendian Feb 08 '14 at 17:54
2 Answers
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);
.

Community
- 1
- 1

Rhitakorrr
- 104
- 4