When I am using (int) with (double) some times it is not working correct.
Look At The PHP Code Example:
I Need To LEAVE 2 Decimals And REMOVE Other...
I Know number_format(); function But I Cannot Use It. Because It Is Rounding Number
number_format(24.299,2);
Output: 24.30
I Need: 24.29
<?php
$str="158.2";
echo (double)$str; // Output: 158.2
echo (double)$str*100; // Output: 15820
echo (int)((double)$str*100); // Output: 15819 <-WHY? It Must To Be 15820, Why 15819?
echo ((int)((double)$str*100)/100); // Output: 158.19
?>
I need To leave two decimals in the number and cut other WITHOUT rounding.
Never cast an unknown fraction to integers, see the manual on http://www.php.net/manual/en/language.types.integer.php.
(int) ( (0.1+0.7) * 10 );
will result in 7, not 8 as one might expect. Casting from float to integer will always round down - and you may also want to check the operator precedence http://php.net/manual/en/language.operators.precedence.php.Solution: calculate your fraction before you cast it.
$fStr = (float) $str; $iStr = (int) $fStr;
Because of floating point precision (see for example this question: PHP - Floating Number Precision),
158.2 * 100
is not exactly15820
but something like15819.99999999
.Now
(int)
is for type conversion, not for rounding, and any digits after the point are cut of.This is easy:
Update
number_format
does round, so it is a bit more complicated:bcmul
multiplies with arbitrary precision, in this case 0. Results:This doesn't answer the question of why that happens (it could be a precision bug), but to solve your problem, try using
$foo = sprintf("%.2f", (float)$str);
.Example:
EDIT: Infact, yes, this is a precision issue. (in C++) by printing 158.2 to 20 decimal places, I get the output of "158.19999999999998863132". This is an inherent problem with floating point/double precision values. You can see the same effect by using
echo sprintf("%.20f", $var);
in PHP.First off, PHP is a language that allows you to type juggle. Which means you do not need the
(int)
or the(double)
to do what you're trying to do.Use the
number_format
command to format your numbers how you want.More here
Fixed.