dev740's avatar

Why is the loop printing wrong value?

echo($a[5]); //this is not printing 0 why?

 for($x=-2;$x<2.1;$x+=0.4){
 $a[] = $x*$x;

 }

Output is:

Array
(
    [0] => 4
    [1] => 2.56
    [2] => 1.44
    [3] => 0.64
    [4] => 0.16
    [5] => 1.2325951644078E-32
    [6] => 0.16
    [7] => 0.64
    [8] => 1.44
    [9] => 2.56
   [10] => 4
)
0 likes
2 replies
Jaytee's avatar
Jaytee
Best Answer
Level 39

You can use number_format() or round() to get 2 decimal places, and that'll correct the value to 0.0. If you use number_format, you'll need to convert it to a float. Using round will work (tested), but if precision here is key, then round may not be best suited.

The world of using doubles/floats sucks sometimes :/

Please or to participate in this conversation.