Converting from Decimal degrees to Degrees Minutes Seconds tenths.

Viewed 33989

Is there some sample conversion code in C# to go from decimal degrees to Degrees, Minutes, Seconds, Tenth?

5 Answers

String representation of a location, i.e. 51°09'48.2"N 10°07'28.6"E

public static string ToDMS(this Location location)
{
    var (lat, lon) = (location.Latitude, location.Longitude);
    var latSec = Math.Abs(lat) % 1.0 * 3600.0;
    var lonSec = Math.Abs(lon) % 1.0 * 3600.0;
    return FormattableString.Invariant(
      $@"{Math.Abs((int)lat)}°{(int)latSec / 60}'{latSec % 60:F1}\"{(lat >= 0 ? "N" : "S")
       } {Math.Abs((int)lon)}°{(int)lonSec / 60}'{lonSec % 60:F1}\"{(lon >= 0 ? "E" : "W")}");
}

You might not like this one-liner :)

public static string ToDMS(double lat, double lon) => FormattableString.Invariant($"{Math.Abs((int)lat)}°{(int)(Math.Abs(lat) % 1.0 * 60.0)}'{Math.Abs(lat) * 3600.0 % 60:F1}\"{(lat >= 0 ? "N" : "S")} {Math.Abs((int)lon)}°{(int)(Math.Abs(lon) % 1.0 * 60.0)}'{Math.Abs(lon) * 3600.0 % 60:F1}\"{(lon >= 0 ? "E" : "W")}" );

Suggestions for any improvements welcome...

Related