The Float.parseFloat() static method parses the string argument and returns a float value.
Syntaxpublic static float parseFloat(String s) throws NumberFormatException
The parameter s will be converted to a primitive float value. Note that the method will throw a NumberFormatException if the parameter is not a valid float.
ExampleString numberAsString = "153.25"; float number = Float.parseFloat(numberAsString); System.out.println("The number is: " + number);When you run the code above, the output will show this:
The number is: 153.25This is the most common and popular solution when you need to convert a String to float. Note that the resulting value is not an instance of the Float class but just a plain primitive float value.
The Float.valueOf() static method will return a Float object holding the value of the specified String.
Syntaxpublic static Float valueOf(String s) throws NumberFormatException
Note that the method will throw a NumberFormatException if the parameter is not a valid float.
String numberAsString = "153.25"; float number = Float.valueOf(numberAsString); System.out.println("The number is: " + number);This will output:
The number is: 153.25This is the most common method when you wish to convert a String to Float. Note that the resulting value is an instance of the Float class and not a primitive float value.
Another alternative method is to create an instance of Float class and then invoke it's floatValue() method.
Example
String numberAsString = "153.25"; Float floatObject = new Float(numberAsString); float number = floatObject.floatValue();
We can shorten to:
String numberAsString = "153.25"; float number = new Float(numberAsString).floatValue();or just:
float number = new Float("153.25").floatValue();
String numberAsString = "153.25"; DecimalFormat decimalFormat = new DecimalFormat("#"); try { float number = decimalFormat.parse(numberAsString).floatValue(); System.out.println("The number is: " + number); } catch (ParseException e) { System.out.println(numberAsString + " is not a valid number."); }Will output
The number is: 153.25Note that the parse() method will throw a ParseException when there are problems encountered with the String.