A7med Baraka
05-05-2009, 01:31 AM
convert a String to a float with Java
An example of a simple program that performs this conversion is shown below:
public class s2f {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try {
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
Other notes
Float.toString(float f) is used to convert in the other direction, from a float to a String.
An example of a simple program that performs this conversion is shown below:
public class s2f {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try {
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
Other notes
Float.toString(float f) is used to convert in the other direction, from a float to a String.