title: Convert String to Number, Java
body: <p><strong>Edit: Clarification</strong> convert any valid number encoding from a string to a number</p>
  
  <p>How does one convert a string to a number, say just for integers, for all accepted integer formats, particularly the ones that throw NumberFormatException under Integer.parseInt. For example, the code</p>
  
  <pre><code>...
  int i = 0xff;
  System.out.println(i);
  String s = "0xff";
  System.out.println( Integer.parseInt(s) );
  ....
  </code></pre>
  
  <p>Will throw a NumberFormatException on the fourth line, even though the string is clearly a valid encoding for a hexadecimal integer. We can assume that we already know that the encoding is a valid number, say by checking it against a regex. It would be nice to also check for overflow (like Integer.parseInt does), but it would be okay if that has to be done as a separate step.</p>
  
  <p>I could loop through every digit and manually calculate the composite, but that would pretty difficult. Is there a better way?</p>
  
  <p><strong>EDIT:</strong> a lot of people are answering this for hexidecimal, which is great, but not completely what I was asking (it's my fault, I used hexidecimal as the example). I'm wondering if there's a way to decode <em>all valid java numbers</em>. Long.decode is definitely great for just catching hex, but it fails on </p>
  
  <pre><code>222222L
  </code></pre>
  
  <p>which is a perfectly valid long. Do I have to catch for every different number format separately? I'm assuming you've used a regex to tell what category of number it is, i.e, distinguish floats, integers, etc.</p>