Skip to content

Instantly share code, notes, and snippets.

@felipeskroski-zz
Last active February 24, 2022 20:27
Show Gist options
  • Save felipeskroski-zz/8aec22f01dabdbf8fb6b to your computer and use it in GitHub Desktop.
Save felipeskroski-zz/8aec22f01dabdbf8fb6b to your computer and use it in GitHub Desktop.
Javascript function to convert wind direction in degrees to cardinal.
var degToCard = function(deg){
if (deg>11.25 && deg<=33.75){
return "NNE";
}else if (deg>33.75 && deg<=56.25){
return "ENE";
}else if (deg>56.25 && deg<=78.75){
return "E";
}else if (deg>78.75 && deg<=101.25){
return "ESE";
}else if (deg>101.25 && deg<=123.75){
return "ESE";
}else if (deg>123.75 && deg<=146.25){
return "SE";
}else if (deg>146.25 && deg<=168.75){
return "SSE";
}else if (deg>168.75 && deg<=191.25){
return "S";
}else if (deg>191.25 && deg<=213.75){
return "SSW";
}else if (deg>213.75 && deg<=236.25){
return "SW";
}else if (deg>236.25 && deg<=258.75){
return "WSW";
}else if (deg>258.75 && deg<=281.25){
return "W";
}else if (deg>281.25 && deg<=303.75){
return "WNW";
}else if (deg>303.75 && deg<=326.25){
return "NW";
}else if (deg>326.25 && deg<=348.75){
return "NNW";
}else{
return "N";
}
}
@N2481
Copy link

N2481 commented Apr 18, 2018

If you input deg = 33.75, it will return "N", which is wrong.
You must add "<="
if (deg>11.25 && deg<33.75)
change to:
if (deg>11.25 && deg<=33.75)

for all conditions.

@thovan-bayard
Copy link

https://en.wikipedia.org/wiki/Points_of_the_compass
According to this document, all directions should be 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'
But this function: NNE ENE E ESE ...
Hopes that I was wrong...
Below is my function

function degToCard(value) { value = parseFloat(value); if (value <= 11.25) return 'N'; value -= 11.25; var allDirections = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']; var dIndex = parseInt(value/22.5); return allDirections[dIndex] ? allDirections[dIndex] : 'N'; }

@russellshome
Copy link

The original code seems to have missed NE and put ESE in twice.
thovan-bayard's code is more compact returns the correct value.

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