Convert float to String and String to float in Java

Convert float to String and String to float in Java

To convert a float to a String and a String to a float in Java, you can use the following methods:

  1. Convert float to String:

    You can use the Float.toString(floatValue) method or String.valueOf(floatValue) to convert a float to a String.

    float floatValue = 3.14159f; // Using Float.toString() String floatString1 = Float.toString(floatValue); // Using String.valueOf() String floatString2 = String.valueOf(floatValue); 

    Both of these methods will give you a String representation of the float value.

  2. Convert String to float:

    To convert a String to a float, you can use the Float.parseFloat(stringValue) method or Float.valueOf(stringValue).floatValue().

    String floatString = "3.14159"; // Using Float.parseFloat() float floatValue1 = Float.parseFloat(floatString); // Using Float.valueOf().floatValue() float floatValue2 = Float.valueOf(floatString).floatValue(); 

    Both of these methods will parse the String and return the equivalent float value.

Here's a complete example:

public class FloatToStringAndStringToFloat { public static void main(String[] args) { float originalFloat = 3.14159f; // Convert float to String String floatString = Float.toString(originalFloat); // Convert String to float float parsedFloat = Float.parseFloat(floatString); System.out.println("Original float: " + originalFloat); System.out.println("Float as String: " + floatString); System.out.println("Parsed float: " + parsedFloat); } } 

This code will output:

Original float: 3.14159 Float as String: 3.14159 Parsed float: 3.14159 

Keep in mind that when parsing a String to a float, you should ensure that the String contains a valid float representation; otherwise, a NumberFormatException may be thrown.


More Tags

fxml bufferedimage pikepdf unauthorizedaccessexcepti uikeyinput hal reference getelementsbyclassname azure-log-analytics tiff

More Java Questions

More Mortgage and Real Estate Calculators

More Housing Building Calculators

More Internet Calculators

More Various Measurements Units Calculators