Difference between revisions of "Convert a String to a Number"

From Progzoo
Jump to: navigation, search
(New page: ==String to int== <question xmlns:htm="http://www.w3.org/1999/xhtml" lang="java" className="Demo"><prog> public class Demo{ public static void main(String[] argv) { String s = "123...)
 
 
(5 intermediate revisions by 2 users not shown)
Line 1: Line 1:
==String to int==
+
{{topTenTips}}
 
<question xmlns:htm="http://www.w3.org/1999/xhtml" lang="java" className="Demo"><prog>
 
<question xmlns:htm="http://www.w3.org/1999/xhtml" lang="java" className="Demo"><prog>
 
public class Demo{
 
public class Demo{
Line 9: Line 9:
 
   }
 
   }
 
}
 
}
</prog>
+
</prog>
 
<p>The static method <code>Integer.parseInt</code> will do the trick</p>
 
<p>The static method <code>Integer.parseInt</code> will do the trick</p>
 
<p>There is a danger that the string does not represent a valid
 
<p>There is a danger that the string does not represent a valid
Line 15: Line 15:
 
<p>There are plenty of similar routines such as:
 
<p>There are plenty of similar routines such as:
 
<code>Float.parseFloat Long.parseLong Double.parseDouble
 
<code>Float.parseFloat Long.parseLong Double.parseDouble
Boolean.parseBoolean</code>
+
Boolean.parseBoolean</code>  
 
</p>
 
</p>
The value "1234" is a string, you need to treat it as a number -
+
The value "1234" is a string, you need to treat it as a num ber -
 
to add 1, giving 1235.
 
to add 1, giving 1235.
 
</question>
 
</question>

Latest revision as of 22:33, 9 April 2008

The static method Integer.parseInt will do the trick

There is a danger that the string does not represent a valid number in which case an exception will be raised.

There are plenty of similar routines such as: Float.parseFloat Long.parseLong Double.parseDouble Boolean.parseBoolean

The value "1234" is a string, you need to treat it as a num ber - to add 1, giving 1235.

[Font] [Default] [Show] [Resize] [History] [Profile]