Saturday, March 1, 2008

Convert a String to Number in Java

This 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);

0 comments: