Convert String To Float

In this section, you will learn to convert a numeric
type string value into a float.
Code Description:
This program takes a numeric type string at the
console. The valueOf()
method takes a string type parameter and returns a float object. And the floatValue()
method
returns the float value of this float object. Finally, we get the float type
data.
Float.valueOf(): This is the method that takes a string type
value and returns a float object. If the string is null, then a NullPointerException is thrown.
floatValue():
This method returns the float value of this
float object.
Here
is the code of this program:
import java.io.*;
import java.lang.*;
public class StringToFloat{
public static void main (String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the numeric type string value:");
String str = reader.readLine();
try{
float f = Float.valueOf(str.trim()).floatValue();
System.out.println("Float value is: = " + f);
}
catch (Exception e){
System.out.println("Exception: " + e.getMessage());
}
}
}
|
Download of this program:
Output of this program given below.
C:\corejava>java StringToFloat
Enter the numeric type string value:
50
Float value is: = 50.0
C:\corejava> _ |

|