I am trying to calculate this in php :
echo (int)((0.1 + 0.7) * 20);
why it return 15
Expected result: 16
Actual result:15
I am trying to calculate this in php :
echo (int)((0.1 + 0.7) * 20);
why it return 15
Expected result: 16
Actual result:15
From doc: http://php.net/manual/en/language.types.float.php
Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
you can use BC Math Functions
$precision = 2;
echo bcmul( bcadd("0.1","0.7",$precision) ,"20",$precision); // 16.00
you need
intval ((0.1 + 0.7) * 20);
sorry, it's wrong, but here is a workaround:
$n= ( (0.1 + 0.7) * 20); //=16
$n2 = intval ($n.""); // cast it to string, then to int.
echo $n2;
Type casting the result is leading to a wrong number echo ((0.1 + 0.7) * 20);
should give 16
Looks like a rounding error
0.1 + 0.7 = 0.7999999999
0.799999999 * 20 = 15.9999998
int(15.9999998) = 15
you have to round the result.
echo (int)(((0.1*10 + 0.7*10)/10) * 20);
First you need to get rid of the decimal then perform the operation else don't typecast
echo (0.1+0.7)*20;
did you try this approach? :
<?php
$value = (0.1+0.7)*20;
echo $value;
?>
my result is 16
Please read PHP documentation on foating point numbers. As is written in the documentation,
For example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8.
When working with floating point numbers, use BC Math to get correct results.
Let's be more precise:
printf("%1\$.20f", 0.7); // output: 0.69999999999999995559
printf("%1\$.20f", 0.1); // output: 0.10000000000000000555
printf("%1\$.20f", (0.10000000000000000555+0.69999999999999995559)*20); // output: 15.99999999999999822364
so when you cast the last number to int :
echo (int)15.99999999999999822364; // output: 15