title: Cardinal direction algorithm in Java
body: <p>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 android compass application I'm using). What I ended up with was this:</p>
  
  <pre><code>private String headingToString(Float heading)
  {
      String strHeading = "?";
      Hashtable&lt;String, Float&gt; cardinal = new Hashtable&lt;String, Float&gt;();
      cardinal.put("North_1", new Float(0));
      cardinal.put("Northeast", new Float(45));
      cardinal.put("East", new Float(90));
      cardinal.put("Southeast", new Float(135));
      cardinal.put("South", new Float(180));
      cardinal.put("Southwest", new Float(225));
      cardinal.put("West", new Float(270));
      cardinal.put("Northwest", new Float(315));
      cardinal.put("North_2", new Float(360));
  
      for (String key: cardinal.keySet())
      {
          Float value = cardinal.get(key);
          if (Math.abs(heading - value) &lt; 30)
          {
              strHeading = key;
              if (key.contains("North_"))
              {
                  strHeading = "North";
              }
              break;
          }
      }
      return strHeading;
  }
  </code></pre>
  
  <p>My question is, is this the best way of doing this? It must have been done many times before although I haven't done a search for examples on the web yet. Have any other people tried this and found a neater solution?</p>
  
  <p>Edit for The Reverand's Thilo's, shinjin's and Chrstoffer's responses:</p>
  
  <p><strong>The Solution</strong></p>
  
  <pre><code>public static String headingToString2(double x)
  {
      String directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"};
      return directions[ (int)Math.round((  ((double)x % 360) / 45)) ];
  }
  </code></pre>