Saturday, May 16, 2009

Convert Decimal Degrees to Degrees Minutes Seconds

This post contains C# code to convert decimal degrees into degrees, minute and seconds.  The screenshot below demonstration the code being using to convert a latitude (in decimal degrees) to a correctly formatted DMS value.

Sample application to convert DD to DMS

Here is the code associated with the button that does the conversion.

private void Button_Click(object sender, EventArgs e) {
    if (sender == this.buttonConvertToDms) {
        if (string.IsNullOrEmpty(this.textBoxDD.Text)) { return; }
        double d;
        if (!double.TryParse(this.textBoxDD.Text, out d)) { return; }
        CoordinateType type = this.radioButtonLat.Checked ? CoordinateType.latitude : CoordinateType.longitude;
        this.textBoxDMS.Text = Engine.DDtoDMS(d, type);
    }
    else if (sender == this.buttonClose) {
        this.Close();
    }
}

Lastly, here is the formatting code.  Unlike similar sample, this code will pad minutes and seconds with zeros and append a N, S, W or E compass heading.

public enum CoordinateType { longitude, latitude };
public static string DDtoDMS(double coordinate, CoordinateType type) {
    // Set flag if number is negative
    bool neg = coordinate < 0d;

    // Work with a positive number
    coordinate = Math.Abs(coordinate);

    // Get d/m/s components
    double d = Math.Floor(coordinate);
    coordinate -= d;
    coordinate *= 60;
    double m = Math.Floor(coordinate);
    coordinate -= m;
    coordinate *= 60;
    double s = Math.Round(coordinate);

    // Create padding character
    char pad;
    char.TryParse("0", out pad);

    // Create d/m/s strings
    string dd = d.ToString();
    string mm = m.ToString().PadLeft(2, pad);
    string ss = s.ToString().PadLeft(2, pad);

    // Append d/m/s
    string dms = string.Format("{0}°{1}'{2}\"", dd, mm, ss);

    // Append compass heading
    switch (type) {
        case CoordinateType.longitude:
            dms += neg ? "W" : "E";
            break;
        case CoordinateType.latitude:
            dms += neg ? "S" : "N";
            break;
    }

    // Return formated string
    return dms;
}
Technorati Tags:

5 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. I'd like to do the reverse & return the decimal again from the formatted output.

    Any tips?

    ReplyDelete
  3. In am getting error on "Engine.DDtoDMS(d, type)"

    "The Name Engine doesnt exist in current context"

    ReplyDelete
    Replies
    1. You are a copy/paste developer... just considerer this sample a little bit...
      Engine is a static class, used for this sample.

      Delete
    2. can you give us a hint about that engine code. a new programmer here

      Delete