Java String to float FAQ: How do I convert a Java String to a Java float?
Answer: Here's an example that demonstrates how to convert a Java String to a float value. This example code segment converts the String "100.00" to a Java float:
String s = "100.00"; try { float f = Float.valueOf(s.trim()).floatValue(); System.out.println("float f = " + f); } catch (NumberFormatException nfe) { System.err.println("NumberFormatException: " + nfe.getMessage()); }
As you can see from this Java String to float example, when you convert a String to a float, a NumberFormatException
can be thrown. This can happen any time you attempt to convert a String
that cannot be converted to a number, such as the word "Shobogenzo". While it is a String
, it is not a float
, and therefore the valueOf method throws a NumberFormatException
.
You can convert a Java String to other Java primitive fields as well, including int, long, double, etc., using similar techniques.
Java String to float - Update
As an update to this String to float example, you can also convert a Java String to a Java float field like as shown in this complete Java class:
/** * A Java example class, demonstrates how * to convert a Java String to a Java float. */ public class JavaConvertStringToFloat { public static void main(String[] args) { try { String string = "foo"; float f = Float.parseFloat(string); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } }
Java String to float - Summary
I hope these Java String to float examples have been helpful. As you can see, they're fairly simple, and you just have to deal with the NumberFormatException.