Sunday, December 29, 2013

How to convert Degrees to Cardinal Directions in C#

 

It’s not a difficult problem but considering how many people are likely to use/need this code I found it surprising that I had to do a little digging to find any good examples.

As you can see below, DegreesToCardinal() effectively divides the compass circle into 8 equal sections and then does a quick lookup in the string array.  The extra “N” is for cases when rounding up towards 360.

DegreesToCardinalDetailed() adds in the second intercardinals (thank you Wikipedia).

http://en.wikipedia.org/wiki/Cardinal_direction 

 

And of course, you could make both of these functions safer by making sure you’re not getting an angle less than 0.

 

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)
{
degrees *= 10;

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 % 3600) / 225) ];
}


Happy coding!