If the programming language you're using supports the % (mod) operator on floating point numbers (like Python and Ruby), I'd recommend using that. Otherwise, some other languages (like C and C++) allow you to use fmod().
(Whichever mod operator you use, make sure ahead of time that it will do mod operations on floating-point numbers, and that it'll always give you non-negative answers. Otherwise you'll get a nasty surprise later when many of your lat/lon points are not correct.)
Use it like this:
# Put the longitude in the range of [0,360):
longitude %= 360
# Put the longitude in the range of [-180,180):
if longitude >= 180:
longitude -= 360
If you'd prefer to do it all in one line:
# Put the longitude in the range of [-180,180):
longitude = (longitude + 180) % 360 - 180
These approaches have no loops, so they'll normalize longitude values without needing to repeatedly add or subtract, no matter how many times your observation has circled around the earth.
Edit:
Hmmm... I just noticed that Javascript doesn't seem to handle %
with negative values like I thought it would.
In that case, try this one-liner:
longitude = (longitude + 36180) % 360 - 180
The 36180
we're adding is 36,000 + 180. The 36,000 is to move a negative value into the positive domain, and the 180 is to shift it over so that when it is modded by 360
, it'll be in the range of [0,360). The - 180
part shifts it back to the range of [-180,180).
Here's another one-liner, one that doesn't rely on 36,000 being big enough:
longitude = (longitude % 360 + 360 + 180) % 360 - 180
The longitude % 360 + 360
part will ensure the value stays in the positive domain when it's later modded by 360
. The + 180
part shifts it over so that when it later gets 180 subtracted from it (with - 180
), it'll be in the desired range of [-180,180).