Skip to content

Instantly share code, notes, and snippets.

@wberdowski
Created June 14, 2021 14:38
Show Gist options
  • Save wberdowski/20ebd54f304f96ad204ea0c8dcf1404a to your computer and use it in GitHub Desktop.
Save wberdowski/20ebd54f304f96ad204ea0c8dcf1404a to your computer and use it in GitHub Desktop.
Convert latitude and longitude to DMS (degrees minutes seconds) format
public static class LatLon2Dms
{
public static string Convert(double lat, double lon)
{
return ConvertSingle(lat, true) + ", " + ConvertSingle(lon, false);
}
private static string ConvertSingle(double value, bool isLat)
{
double v = Math.Abs(value);
int deg = (int)Math.Floor(v);
int min = (int)Math.Floor((v - deg) * 60);
int sec = (int)Math.Floor(3600 * (v - deg) - 60 * min);
return $"{deg}° {min}' {sec}\" {GetSuffix(value, isLat)}";
}
private static char GetSuffix(double value, bool isLat)
{
bool isNegative = (Math.Sign(value) == -1);
if (isLat)
{
if (isNegative)
{
return 'S';
} else
{
return 'N';
}
} else
{
if (isNegative)
{
return 'W';
} else
{
return 'E';
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment