Java Program to Convert String to Float Value
Given a string “str” in Java, the task is to convert this string to float type.
This can be done by two methods as listed below:
- Using parseFloat() Method
- Using valueOf() Method
Let us discuss above two ways of implementing the methods to get a fair understanding of the conversion of string to float values.
Method 1: Using parseFloat()
The parseFloat() method in Float Class is a built-in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float.
public static float parseFloat(String s) ;
Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
Return type: It returns e float value represented by the string argument.
- NullPointerException: When the string parsed is null
- NumberFormatException: When the string parsed does not contain a parsable float
String is converted to float 100.0
Example 2: To show unsuccessful conversion
Method 2: Using valueof() method
The valueOf() method of the Float class converts data from its internal form into human-readable form. The valueOf() method converts data from its internal form into a human-readable form. It is a static method that is overloaded within a string for all of Java’s built-in types so that each type can be converted properly into a string.
It is called when a string representation of some other type data is needed-for example during concatenation operation.you can call this method with any data type and get a reasonable String representation valueOf() returns java.lang.Integer, which is the object representative of the integer Few forms of valueOf()
- It returns string representation of given value
- valueOf(iNum); // Returns the string representation of int iNum.
- String.valueOf(sta); // Returns the string representation of the boolean argument.
- String.valueOf(fNum); // Returns the string representation of the float fnum.
- String.valueOf(data, 0, 15); // Returns the string representation of a specific subarray of the chararray argument.
- String.valueOf(data, 0, 5); // Returns the string of charArray 0 to 5
- String.valueOf(data, 7, 9); // Returns the string of charArray starting index 7 and total count from 7 is 9.
1.0 after converting into float = 1.0