Convert String to Float and Back in Java
Converting Strings to Floats and Back in Java
Java, as a powerful language, provides several methods for handling data types. Converting from Strings to floats or vice versa is one of the operations which is used often in coding. In this article, we will look at how we can convert a String to a float and then convert it back.
Converting String to Float
Java provides us with two ways to convert String to a float. The first one is by using the parseFloat() method which parses a String and returns the corresponding float value. The syntax for this method is:
float floatValue = Float.parseFloat(string);
For example, if we want to convert the String "3.14" to float we can use the following statement:
float floatValue = Float.parseFloat("3.14");
The second method is by using the valueOf() method which takes a String argument and returns the corresponding Float object. The syntax for this method is:
Float floatObject = Float.valueOf(string);
For example, if we want to convert the same String "3.14" to Float, we can use the following statement:
Float floatObject = Float.valueOf("3.14");
Converting Float to String
Converting a float to a String is a little more straightforward as compared to the other way around. Java provides us with two ways to achieve this as well. The first one is by using the toString() method which takes a float value as an argument and returns its corresponding String representation. The syntax for this method is:
String stringValue = Float.toString(floatValue);
For example, if we want to convert 3.14f to a String we can use the following statement:
String stringValue = Float.toString(3.14f);
The second method is by using the String.valueOf() method which takes a float value as an argument and returns its corresponding String representation. The syntax for this method is:
String stringValue = String.valueOf(floatValue);
For example, if we want to convert the same float value 3.14f to a String, we can use the following statement:
String stringValue = String.valueOf(3.14f);
Conclusion
In this article, we looked at how we can convert a String to a float and back in Java. We saw that there are two methods for converting a String to a float, parseFloat() and valueOf(). For converting a float to a String, there are two methods available, toString() and String.valueOf().