How to Convert a String value to Float value in Java with Examples
Given a String “str” in Java, the task is to convert this string to float type.
Examples:
Input: str = "1.0"
Output: 1.0
Input: str = "3.14"
Output: 3.14
Approach 1: (Naive Method)
One method is to traverse the string and add the numbers one by one to the float type. This method is not an efficient approach.
Approach 2: (Using Float.parseFloat() method)
The simplest way to do so is using parseFloat() method of Float class in java.lang package. This method takes the string to be parsed and returns the float type from it. If not convertible, this method throws error.
Syntax:
Float.parseFloat(str);
Below is the implementation of the above approach:
Example 1: To show successful conversion
class GFG {
public static float convertStringToFloat(String str)
{
return Float.parseFloat(str);
}
public static void main(String[] args)
{
String stringValue = "1.0" ;
float floatValue;
floatValue = convertStringToFloat(stringValue);
System.out.println(
stringValue
+ " after converting into float = "
+ floatValue);
}
}
|
Output:
1.0 after converting into float = 1.0
Example 2: To show unsuccessful conversion
class GFG {
public static void convertStringToFloat(String str)
{
float floatValue;
try {
floatValue = Float.parseFloat(str);
System.out.println(
str
+ " after converting into float = "
+ floatValue);
}
catch (Exception e) {
System.out.println(
str
+ " cannot be converted to float: "
+ e.getMessage());
}
}
public static void main(String[] args)
{
String str1 = "" ;
String str2 = null ;
String str3 = "GFG" ;
convertStringToFloat(str1);
convertStringToFloat(str2);
convertStringToFloat(str3);
}
}
|
Output:
cannot be converted to float: empty String
null cannot be converted to float: null
GFG cannot be converted to float: For input string: "GFG"
Approach 3: (Using Float.valueOf() method)
The valueOf() method of Float class converts data from its internal form into human-readable form.
Syntax:
Float.valueOf(str);
Below is the implementation of the above approach:
Example 1: To show successful conversion
class GFG {
public static float convertStringToFloat(String str)
{
return Float.valueOf(str);
}
public static void main(String[] args)
{
String stringValue = "1.0" ;
float floatValue;
floatValue = convertStringToFloat(stringValue);
System.out.println(
stringValue
+ " after converting into float = "
+ floatValue);
}
}
|
Output:
1.0 after converting into float = 1.0
Last Updated :
29 Jan, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...