Skip to content

Instantly share code, notes, and snippets.

@adrianstevens
Created December 28, 2013 19:29
Show Gist options
  • Save adrianstevens/8163205 to your computer and use it in GitHub Desktop.
Save adrianstevens/8163205 to your computer and use it in GitHub Desktop.
Compass heading to cardinal direction in c#
public static string DegreesToCardinal(double degrees)
{
string[] caridnals = { "N", "NE", "E", "SE", "S", "SW", "W", "NW", "N" };
return caridnals[ (int)Math.Round(((double)degrees % 360) / 45) ];
}
public static string DegreesToCardinalDetailed(double degrees)
{
string[] caridnals = { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N" };
return caridnals[ (int)Math.Round(((double)degrees*10 % 3600) / 225) ];
}
@programmingworld1
Copy link

Looks great but doesnt work

@JohnSpahr
Copy link

JohnSpahr commented Oct 11, 2019

Looks great but doesnt work

I got it to work. Thanks for the code, this calculation is very handy!

My implementation:

void Compass_ReadingChanged(object sender, CompassChangedEventArgs e)
{
     var data = e.Reading;
     var degrees = e.Reading.HeadingMagneticNorth;
     string[] caridnals = { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N" };
     var test = caridnals[(int)Math.Round(((double)degrees * 10 % 3600) / 225)];
     directionLbl.Text = test.ToString();
}

I hope this helps someone!

@quicoli
Copy link

quicoli commented Aug 6, 2020

@JohnSpahr thanks, this helped me :)

@JohnSpahr
Copy link

@quicoli Awesome! Glad it worked

@LGM-AdrianHum
Copy link

LGM-AdrianHum commented May 15, 2021

It still needs conversion for negative degrees...

var degrees = e.Reading.HeadingMagneticNorth<0 ? 360+e.Reading.HeadingMagneticNorth : e.Reading.HeadingMagneticNorth;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment