Hi,
I've just forked JStott's PHPCoord also. I'm not proposing any merge as I need to maintain compatibility with <5.3 PHP. This is just a heads up really.
I discovered that I was getting different values out of toSixFigureString()
, when compared to the javascript version of the same library - and the javascript version gives the correct results.
I found the source of the error in the use of the 2 round()
functions on the last few lines of the function - these were only introduced in version 2.3, having previously been floor()
. Both of these should be floor()
. I've been trying to contact the original developer to discuss why he made this change, but to no avail.
Here's a worked example:
$Easting = 439145
$Northing = 274187
This is a point in warwickshire, where the A45 meets the A445 (near Ryton-on-Dunsmore. Converting these by hand is simple. Chop off the 1st digit (they're taken care of by the letters in the reference - and they get converted properly by the function to SP) and the remaining digits give you the rest of the reference:
SP 39145 74187
To convert this to a six figure reference, chop off (don't round - that might put you in the wrong square) the last 2 digits of the easting and northing to give you:
SP 391 741
It's easy to see that rounding 74187 to 3 digits would give you 742 - which is not correct. But let's work through the function manually:
$100kmE = floor(439145/100000) = 4
$100kmN = floor(274187/100000) = 2
We'll assume the calculation of the 2 letters gives us SP. The digits after the SP are calculated thusly:
$e = $Easting - (100000 * $100kmE) = 439145 - 400000 = 39145
$n = $Northing - (100000 * $100kmN) = 274187 - 200000 = 74187
So, the full 10 digit OS grid coordinate would be SP 39145 74187. And we're right so far.
To get the 6 digit grid, we just chop the last 2 digits off each of the easting and northing to give us SP 391 741. The correct function to use for this is floor(), not round():
floor(39145/100) = 391
floor(74187/100) = 741
Using round()
, as in the broken version, gives us
round(39145/100) = 391 // (still OK)
round(74187/100) = 742 // (oops)
And therefore, the incorrect OS grid SP 391 742, which is what we'd been seeing from v2.3 of JStott's code.
This suggests to me that 50% of values calculated by this function will be wrong. If the 4th digit is >5, you'll get the wrong result. Otherwise, it'll be correct. Interesting to note that the examples in the original distribution are OK, perhaps by chance.
Sorry for the long windedness, but this has been driving me mad! And so many emails to the dev with no response, I feel like I've been banging my against the wall!
Let me know if you need any more clarification! And I hope this helps.