String to float Conversion in Java

String to float Conversion: Sometimes, we obtain the values in string format in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints.

For example, a float value is obtained in string format as in command-line arguments or from TextField's getText() method. The string value is to be converted into float format to use in caluclations as strings (or any objects in Java) cannnot be multiplied or used in any arithmetic operation. To convert, casting does not work as string and float are incompatable for conversion either implicitly or explicitly. It requires extra effort in coding known as "parsing operation". Parsing operation involves the usage of a wrapper class and parseXXX() method. For string to float conversion, it is required Float class and parseFloat() method and explained in the following program.

Parsing Example on String to float Conversion
public class Conversions
{
   public static void main(String args[])
   {
     String str = "10.5f";                                     // suffix f for float value
     System.out.println("10.5 in String form: " + str);        // printing is no problem, but str * str raises error

     float f1 = Float.parseFloat(str);                         // String to float conversion

     System.out.println("10.5 in float form: " + f1);
     System.out.println("Square of float 10.5: " + f1 * f1);   // using float value in multiplication, prints 110.25
   }
}


String to float
Output screenshot on String to float Example

parseFloat() is a method of wrapper class Float which converts string str to float f1. Now f1 can be used in arithmetic operations.

Using the same technique, it is possible to convert string to other data types byte, short, int, long, double, character and boolean.

Note: The other way float to string is also possible.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.