title: Reading <input> values as numbers and not strings (JavaScript)
body: <p>Let's assume we have a text-box on the page:  </p>
  
  <pre><code>&lt;input type="text"&gt;  
  </code></pre>
  
  <p>The visitor types in some characters, and we read those characters via the <code>value</code> property of the text-box.  </p>
  
  <p>Now, let's say that the text-box represents a numeric value. I cannot define such a thing on the text-box - its value is always going to be a string value. What I can do is, convert that sting value into a numeric value:  </p>
  
  <pre><code>Number(input.value)
  </code></pre>
  
  <p>However, the input value is treated as a <em>StringNumericLiteral</em>, and not a <em>NumericLiteral</em>. That means that these input values are allowed (although they are not numeric literals in JavaScript):</p>
  
  <ul>
  <li>values with leading zeros (like "000003")</li>
  <li>the "Infinity" value</li>
  <li>values with a plus sign (like "+3")</li>
  </ul>
  
  <p>Now, let us say that - for the sake of the argument - I really want to read the input value as <em>NumericLiteral</em>. I don't want numbers with leading zeros or the + sign, etc. I was thinking how I could accomplish this, and this is what I came up with:  </p>
  
  <pre><code>try  {                  
      var n = JSON.parse('{ "n": ' + this.value + ' }').n;
      if (typeof n !== "number") {
          throw "error";
      }
      // n is a Number value that represents the value of the text-box        
  } catch(e) {}
  </code></pre>
  
  <p>This is a simplified version of the code, a live demo is available here:<br>
  <a href="http://vidasp.net/tinydemos/input-as-number.html" rel="nofollow">http://vidasp.net/tinydemos/input-as-number.html</a>  </p>
  
  <p>Note: I use try-catch because if the input value is not a valid JSON value, the JSON.parse call will fail (throw an error).  </p>
  
  <p>So, what do you think of this method. Does it have flaws?</p>
  
  <p>(One downside is that hex numeric values cannot be read, because JSON does not allow them.)  </p>
  
  <p><em><strong>I just realized ...</em></strong>  </p>
  
  <p>... that the reason why I was trying to do this was not to actually read the input as a number. What I wanted is to check whether the value complied to the NumericLiteral grammar - which is something that a regexp check can do easily. </p>