This weekend I spend a few minutes thrashing together an algorithm that would take in a heading (in degrees) and return a String for the cardinal direction (I\'m using it in an
Most of the answers here are off by 22.5 degrees for their 45 degree intervals, and map e.g. 0-45 as N, rather than [337.5-360],[0-22.5] to N. You need to offset before doing the math to correct for this.
Here's a solution that uses 22.5 degree intervals, such as you might see for wind directions:
private String formatBearing(double bearing) {
if (bearing < 0 && bearing > -180) {
// Normalize to [0,360]
bearing = 360.0 + bearing;
}
if (bearing > 360 || bearing < -180) {
return "Unknown";
}
String directions[] = {
"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW",
"N"};
String cardinal = directions[(int) Math.floor(((bearing + 11.25) % 360) / 22.5)];
return cardinal + " (" + formatBearing.format(bearing) + " deg)";
}