Convert a String to Number in Java

This Java tutorial will show you how to convert a string to different number types. Each number type in Java has a parse method that allows you convert a string into the primitive type.

When converting a string to a number, the parse method may throw a NumberFormatException if the string is null or an invalid representation for that type.

Convert a String to an int
To convert a String to an int, call the static method parseInt() on the Integer class. Below is an example:

String string = "123";
int value = Integer.parseInt(string);
Convert a String to a long
To convert a String to a long, call the static method parseLong() on the Long class. Below is an example:
String string = "123";
long value = Long.parseLong(string);

Convert a String to a float
To convert a String to a float, call the static method parseFloat() on the Float class. Below is an example:
String string = "123.4";
float value = Float.parseFloat(string);

Convert a String to a double
To convert a String to a double, call the static method parseDouble() on the Double class. Below is an example:
String string = "123.4";
double value = Double.parseDouble(string);


4 comments:

Anonymous said...

The example does not work as given for jdk1.6.0_12. I get the following error:
"cannot find symbol
symbol : method ParseInt(java.lang.String)
location : class java.lang.Integer
int first = Integer.ParseInt( args[0] );

Gizmo said...

It looks like you have a typo. It should be Integer.parseInt() with a lower case p.

Mr Bond said...

Like it!

Anonymous said...

Why don't I get a value of 0 when i convert "None" ?

Post a Comment