How to Convert String to Float in Java
Open the IDE., Copy and paste the following code: class Convert { public static void main(String[] args) { try { String str = "124863.02"; float num = (Float.parseFloat(str))+36.97; System.out.println(num); } catch(NumberFormatException e) {...
Step-by-Step Guide
-
Step 1: Open the IDE.
Open your IDE of choice, or write the code in a text editor and run it through the Command Prompt. ,, The output will be
124899.99., Once you understand how this simple version works, you'll be able to convert String to Float in more complicated contexts.
You declare a String variable str with the value "124863.02".
Next, you use the wrapper class for Float to parse the String value, assign it to a new Float variable num, and add
36.97 to the assigned value.
Then you print the new Float value of variable num as
124899.99.
You use the try-catch block to counter a NumberFormatException and print a corresponding error message. -
Step 2: Copy and paste the following code: class Convert { public static void main(String[] args) { try { String str = "124863.02"; float num = (Float.parseFloat(str))+36.97; System.out.println(num); } catch(NumberFormatException e) { System.out.println("Invalid String for conversion to Float"); } } }
-
Step 3: Run the program.
-
Step 4: Understand what the program does.
Detailed Guide
Open your IDE of choice, or write the code in a text editor and run it through the Command Prompt. ,, The output will be
124899.99., Once you understand how this simple version works, you'll be able to convert String to Float in more complicated contexts.
You declare a String variable str with the value "124863.02".
Next, you use the wrapper class for Float to parse the String value, assign it to a new Float variable num, and add
36.97 to the assigned value.
Then you print the new Float value of variable num as
124899.99.
You use the try-catch block to counter a NumberFormatException and print a corresponding error message.
About the Author
Samantha Gonzales
Committed to making crafts accessible and understandable for everyone.
Rate This Guide
How helpful was this guide? Click to rate: