public class StringToFloatExample
{
public static void main(String args[])
{
String s = "23.6";
float f = Float.parseFloat(s);
System.out.println(f);
}
}
Explanation for the above code step-by-step
1. Class Declaration:
private class StringToFloatExample {
Declares the class StringToFloatExample. This is the main class that contains the logic for converting a string to a float.
2. Main Method:
public static void main(String args[]) {
The main() method is the entry point for the Java program. This method is where the execution begins.
3. String Declaration:
String s = “23.6”;
- A String variable s is declared and initialized with the value “23.6”.
- This is a floating-point number represented as a string, but the above cannot be used directly within an arithmetic expression or computation due to its data type. This should be evaluated into a number type, specifically float.
4. Converting String to Float:
float f = Float.parseFloat(“23.6”);
- The Float.parseFloat() function evaluates the string “23.6” to a floating-point number type.
- In this expression f = f(); The given expression is evaluated parsing the string \ “23.6 “, whose result will go into a floating point number to the float called f.
- The variable value of f in this instance, is 23.6f. By which f suffices for denoting a floating literal.
5.Print floating Value :
System.out.println(f);
The println() method prints the value of the variable f to the console. Since f is now a float type, it will print the numeric value 23.6.
Output of the Program:
When the program is run, the following output will be printed to the console:
23.6
Explanation of the Output:
The method of Float.parseFloat(“23.6”) converts the string “23.6” into a float value, which is 23.6. The value is printed.
Key Points:
- Float.parseFloat(s): This function takes a string that can represent a float and returns the string as a float. It should be able to represent a valid floating point number, for example, “23.6”, “0.5”, “-12.34”, etc.
- If the string has characters that are not parsable as a number (like “”abc””), then it will throw a NumberFormatException.
Example:
String s = “23.6”; // String representing a floating-point value
float f = Float.parseInt(s); // Convert the string to float
System.out.println(f); // Print the float value: 23.6