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.
like now value of variable will be
$var='2.50';
echo $var
keep in mind this value is coming from mysql databse
but when i use round php function
i got round but i dont need round, i just need to delete all digits after 2 decimal simple.
i have tired, flot()
and lot of other option no success.
Thanks
TL;DR:
The PHP native function bcdiv seems to do precisely what is required, and properly.
To simply "truncate" a number,
bcdiv($var, 1, 2);
where 2 is the number of decimals to preserve (and 1 is the denomenator - dividing the number by 1 allows you to simply truncate the original number to the desired decimal places)Full Answer (for history)
This turns out to be more elusive than one might think.
After this answer was (incorrectly) upvoted quite a bit, it has come to my attention that even sprintf will round.
Rather than delete this answer, I'm turning it into a more robust explanation / discussion of each proposed solution.
number_format - Incorrect. (rounds)
Try using number format:
If you want it to be a number, then simply type-cast to a float:
Note: as has been pointed out in the comments, this does in fact round the number.
sprintf - incorrect. (sprintf also rounds)
If not rounding the number is important, then per the answer below, use sprintf:
floor - not quite! (floor rounds negative numbers)
floor, with some math, will come close to doing what you want:
Where 100 represents the precision you want. If you wanted it to three digits, then:
However, this has a problem with negative numbers. Negative numbers still get rounded, rather than truncated:
"Old" Correct answer: function utilizing floor
So a fully robust solution requires a function:
Results from the above function:
New Correct Answer
Use the PHP native function bcdiv