Convert String to Float in Java

Java is a robust, statically typed programming language that ensures type safety. Type conversions are crucial for processing and manipulating different data forms. This blog covers essential methods to convert String to float in Java, including `Float.parseFloat()`, `Float.valueOf()`, and handling potential exceptions.

How to Convert String to Float in Java?

Convert String to Float in Java Using valueOf() method

// Convert String to Float in Java
class StringtoFloat {
  public static float strToFloat(String str) {
    return Float.valueOf(str);
  }
  public static void main(String[] args) {
    String str = "3.987";
    float floatVal;
    // Convert string to float
    floatVal = strToFloat(str);
    System.out.println(str + " converted to float becomes --> " + floatVal);
  }
}

Explanation of the code:
The `StringtoFloat` class contains a method `strToFloat` that converts a given String to a float using `Float.valueOf(str)`. The `main` method demonstrates this conversion. 

  • First, a String `str` with the value “3.987” is defined. The `strToFloat` method is called with `str` as an argument, converting the string “3.987” to a float. 
  • The resulting float value is assigned to `floatVal`. Finally, the original string and its converted float value are printed to the console. 
  • The `Float.valueOf(str)` method converts the string to a `Float` object, which is then unboxed to a primitive float. 
  • This approach ensures that the string representation of a floating-point number is correctly parsed and converted to a float.

Output:

3.987 converted to float becomes --> 3.987

Convert String to Float in Java using parseFloat() method

// Convert String to Float in Java
class StringtoFloat {
 public static void strToFloat(String s) {
    float floatVal;
    try {
      // Using parseFloat()
      floatVal = Float.parseFloat(s);
      System.out.println(s + " converted to float becomes --> " + floatVal);
    } catch (Exception e) {
      // Print the error
      System.out.println("Error occured:- " + e);
    }
  }
  public static void main(String[] args) {
    String str = "20";

    // Calling the strToFloat() method
    strToFloat(str); 
  }
}

Explanation of the Code:

The `StringtoFloat` class includes the `strToFloat` method, which converts a given string to a float using `Float.parseFloat(s)`. In the `strToFloat` method, a try-catch block handles potential exceptions. Inside the try block, `Float.parseFloat(s)` converts the string `s` to a float, which is then printed to the console. If an exception occurs, it is caught, and an error message is printed.

In the `main` method, a string `str` with the value “20” is defined. The `strToFloat` method is called with `str` as its argument, demonstrating the conversion process. This example showcases error handling during the conversion, ensuring that any invalid input is managed gracefully by printing an appropriate error message.

Output:

20 converted to float becomes --> 20.0

Convert String to Float in Java using Constructors

// Convert String to Float in Java
class StringtoFloat {
  public static float strToFloat(String str) {
    // using the constructor
    float floatVal = new Float(str);
    return floatVal;
  }
  // driver code
  public static void main(String[] args) {
    String str = "70";
    float floatVal;
    // convert string to float
    floatVal = strToFloat(str);
    System.out.println(str + " converted to float becomes --> " + floatVal);
  }
}

Explanation of the code:
The `StringtoFloat` class contains the `strToFloat` method, which converts a string to a float using the `Float` constructor. In the `strToFloat` method, a new `Float` object is created with the string `str` as its argument, which is then unboxed to a primitive float and assigned to `floatVal`. The method returns this float value.

In the `main` method, a string `str` with the value “70” is defined. The `strToFloat` method is called with `str` as its argument, converting the string “70” to a float. The resulting float value is stored in `floatVal` and printed to the console. This code demonstrates how to convert a string to a float using the `Float` constructor, showcasing an alternative to the more commonly used `parseFloat` method.

Output:

70 converted to float becomes --> 70.0

Error Handling

Below is the list of common pitfalls and error handling while you convert string to float:

1. Empty Strings

One common pitfall when converting a string to a float is encountering an empty string, attempting to parse an empty string results in a `NumberFormatException`.

Example:

try {
    String str = "";
    float floatVal = Float.parseFloat(str);
} catch (NumberFormatException e) {
    System.out.println("Error: Input string is empty");
}

2. Invalid Formats

Another frequent issue is dealing with strings that contain non-numeric characters. Such strings will also cause a `NumberFormatException`.

Example:

try {
    String str = "abc";
    float floatVal = Float.parseFloat(str);
} catch (NumberFormatException e) {
    System.out.println("Error: Input string is not a valid number");
}

3. Handling Different Locales

Different locales might use different decimal separators, such as commas instead of periods. Using `NumberFormat` can help manage these differences.

Example:

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public static float strToFloatWithLocale(String str, Locale locale) {
    try {
        NumberFormat format = NumberFormat.getInstance(locale);
        Number number = format.parse(str);
        return number.floatValue();
    } catch (ParseException e) {
        System.out.println("Error: Unable to parse number with locale");
        return 0.0f;
    }
}

4. Null Strings

Passing a null string to the conversion method will cause a `NullPointerException`. Always check for null before attempting conversion.

Example:

try {
    String str = null;
    if (str == null) {
        throw new NullPointerException("Input string is null");
    }
    float floatVal = Float.parseFloat(str);
} catch (NullPointerException | NumberFormatException e) {
    System.out.println("Error: " + e.getMessage());
}

5. Leading and Trailing Spaces

Strings with leading or trailing spaces can also cause issues. It’s a good practice to trim the string before conversion.

Example:

try {
    String str = " 123.45 ";
    float floatVal = Float.parseFloat(str.trim());
    System.out.println("Converted float: " + floatVal);
} catch (NumberFormatException e) {
    System.out.println("Error: Input string is not a valid number");
}

6. Large or Small Numbers

Very large or very small numbers might result in `Infinity` or `-Infinity`. Always validate the range of the float value after conversion.

Example:

try {
    String str = "1e40"; // Exceeds float range
    float floatVal = Float.parseFloat(str);
    if (Float.isInfinite(floatVal)) {
        System.out.println("Error: Number out of range");
    } else {
        System.out.println("Converted float: " + floatVal);
    }
} catch (NumberFormatException e) {
    System.out.println("Error: Input string is not a valid number");
}

Best Practices for Error Handling

  • Always Validate Input: Ensure the input string is not null, empty, or improperly formatted before attempting conversion.
  • Use Try-Catch Blocks: Handle potential exceptions gracefully to prevent program crashes.
  • Trim Strings: Remove leading and trailing spaces to avoid unnecessary errors.
  • Check Range: Validate the resulting float value to ensure it’s within acceptable bounds.
  • Provide Meaningful Messages: Give clear and informative error messages to help debug issues quickly.

By anticipating these common pitfalls and implementing robust error handling, you can make your convert string-to-float in Java conversion process more reliable and user-friendly.

In this blog, we explored various methods to convert strings to floats in Java, including `Float.parseFloat()`, `Float.valueOf()`, and handling exceptions. We highlighted best practices and common pitfalls. We encourage you to experiment with these techniques. For more programming resources, visit Newtum for user-friendly blogs and courses. Happy coding!

Convert String to Float in Java- FAQs

What method is used to convert string to float in Java?

Use Float.parseFloat() or Float.valueOf() to convert a string to a float.

How do you handle a NumberFormatException when converting a string to a float?

Use a try-catch block to catch and handle NumberFormatException.

Can empty strings be converted to floats in Java?

No, converting an empty string to a float will throw a NumberFormatException.

What happens if you pass a null string to the strToFloat method?

Passing a null string will result in a NullPointerException.

Can different locales be handled when converting strings to floats?

Yes, use NumberFormat with the desired locale to parse the string correctly.

About The Author

Leave a Reply