Convert float to String and String to float in Java
To convert a float to a String in Java, you can use the Float.toString
method or the String.valueOf
method. For example:
float f = 3.14f;
// Using Float.toString
String s1 = Float.toString(f);
// Using String.valueOf
String s2 = String.valueOf(f);
To convert a String to a float in Java, you can use the Float.parseFloat
method. For example:
String s = "3.14";
float f = Float.parseFloat(s);
Keep in mind that the parseFloat
method will throw a NumberFormatException
if the string is not a valid float. You should handle this exception appropriately.
I hope this helps! Let me know if you have any questions.