ProblemHelpPlease Posted April 23, 2008 Share Posted April 23, 2008 I have a script that adds markers to a map based on latitude and longitude. To prevent to markers appearing on top of each other I am searching my database of markers and moving the marker to the right slightly if a current marker exists. The problem is that the markers stop moving to the right after the 3rd run through a while loop. I have managed to trace the error in the code. Below is an example of the part of the code that fails. <?php $z = -8.1; $arr = array("-2.1", "-11.1", "0.1", "-3.1", "-4.1", "-5.1", "-6.1", "-7.1", "-8.1", "-0.1", "1.1", "3.1", "2.1", "0.1"); while(in_array($z, $arr)) { $z = $z + 1; } echo "final number ".$z . "<br>"; ?> This code should output the final number as -1.1 but when I run it it returns -3.1 If I use the same code but remove the - and the decimal place from the script then it works perfectly. Any ideas as to what is wrong ??? Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted April 23, 2008 Share Posted April 23, 2008 You are seeing a side effect of how numbers are stored internally. Decimal numbers can not be represented exactly as binary numbers, so the condition fails. Change the loop to: <?php while(in_array(number_format($z,1), $arr)) { $z++; }?> Ken Quote Link to comment Share on other sites More sharing options...
ProblemHelpPlease Posted April 23, 2008 Author Share Posted April 23, 2008 I thought it might be related to how many values could be stored. The numbers that the main script is using very from -11.999999 to 3.999999(theyalways have 6 digits after the decimal place and need to maintain this format when output from the while loop), and I am tring to add 0.0005 to the value if it already exists in the array. Do I need to make a change to the "number_format($z,1)" I haven't used number_format before so i'm still getting my head around how its working. Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted April 23, 2008 Share Posted April 23, 2008 When you're unfamiliar with a function, the best place to turn is the manual: number_format(). The second argument to the number_format() function is the number of decimal places. Ken Quote Link to comment Share on other sites More sharing options...
ProblemHelpPlease Posted April 23, 2008 Author Share Posted April 23, 2008 Thanks for the help ken I'd looked at the manual but was confused with the various options. I've implemented your code changed the decimal place value to 6 and it works ok now. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.