Table of contents
1.
Introduction
2.
String to Float
2.1.
✨Float.parseFloat()
2.2.
✨DecimalFormat
2.3.
✨Float‘s Constructor
3.
Float to String
3.1.
✨String Concatenation
3.2.
✨String.valueOf()
3.3.
✨DecimalFormat
4.
 
5.
Frequently Asked Questions
5.1.
What are a string and a float?
5.2.
What is a concat function in Java?
5.3.
How do you link two strings in Java?
5.4.
Can we add two strings in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to convert String to Float in Java?

Author Manshi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

With few implementation requirements, Java is a high-level, class-based, object-oriented programming language. Because it is a general-purpose programming language, compiled Java code can run on any platform that supports Java without the need for recompilation. This is known as writing once and running anywhere (WORA).

Regardless of computer architecture, Java applications are often compiled to bytecode that is able to run on any Java virtual machine (JVM). Although Java's syntax is comparable to those of C and C++, neither language offers as many low-level features as Java.

This article will highlight and compare all of the available options.

string to float conversion

Let's take a look at the most common methods for converting Float values to String and then we will discuss conversion of String to Float in java.

Also see about Iteration Statements in Java and Duck Number in Java.

String to Float

Let's look at the most typical methods for converting String to Float in java.

✨Float.parseFloat()

One of the most common approaches for converting string to float in java is to use the static method of Float: parseFloat (). The String argument is used to represent a primitive float value, which will be returned. Leading and trailing whitespaces are also ignored:

public class Main {
    public static float convertingStringToFloat(String str)
    {
        return Float.parseFloat(str);
    }
    public static void main(String args[]) {
        // The string value
        String mystringValue = "1.250";
  
        float floatVal;
        // Convert string to float
        floatVal = convertingStringToFloat(mystringValue);
  
        System.out.println(
            mystringValue
            + " after converting to float results in "
            + floatVal);
    }
}
Output

💥If the String argument is null, we get a NullPointerException:

String givenStringvar = null;
assertThrows(NullPointerException.class, () -> Float.parseFloat(givenStringvar));

💥If the String argument does not contain a parsable float, a NumberFormatException is thrown.

String givenStringvar = "3.23x";
assertThrows(NumberFormatException.class, () -> Float.parseFloat(givenStringvar));

✨DecimalFormat

We can also use DecimalFormat to convert String to Float in java . One of the primary benefits is the ability to specify custom decimal point separators.

String givenStringvar = "3,250";
DecimalFormatSymbols mysymbols = new DecimalFormatSymbols();
mysymbols.setDecimalSeparator(',');
DecimalFormat mydecimalFormat = new DecimalFormat("#.000");
mydecimalFormat.setDecimalFormatSymbols(mysymbols);
Float res = decimalFormat.parse(givenStringvar).floatValue();
assertEquals(3.25f, res);
Type conversion

✨Float‘s Constructor

Finally, we can perform the string to float in java conversion directly using Float's function Object(). Internally, it will create the Float object by calling the static parseFloat() method of Float:

String givenStringvar = "3.25";
Float res = new Float(givenStringvar);
assertEquals(3.25f, res);

This function Object() is no longer supported as of Java 9. Instead, we should think about using other static factory methods like parseFloat() or function valueOf(). Try this code by yourself on Online Java Compiler.

Must Read Conditional Statements in Java, Why is Java Platform Independent

See more, Solid Principles in java

Float to String

Converting data from Float to String and vice versa is a common Java operation. However, the numerous options may cause confusion and uncertainty about which to select.

✨String Concatenation

Concatenating the floating-point value with an empty String is the most straightforward solution we have.

Consider the following example:

float givenFloatvar = 2.25f;
String res = givenFloatvar + "";
assertEquals("2.25", res);

💥If the Float object is null, the concatenated string will be "null":

Float givenFloatvar = null;
String res = givenFloatvar + "";
assertEquals("null", res);
type conversions

✨String.valueOf()

Likewise, we can also use the static function valueOf() method of String:

Float givenFloatvar = 3.25f;
String res = String.valueOf(givenFloatvar);
assertEquals("3.25", res);

💥String.valueOf(), unlike Float.toString(), If we pass null as an argument, no exception is thrown; Instead, the String "null" is returned:

Float givenFloatvar = null;
String res = String.valueOf(givenFloatvar);
assertEquals("null", res);

✨DecimalFormat

The format() method of the DecimalFormat class allows you to convert floating-point values to custom formatted Strings. The benefit is that we are able to specify how many decimals we want in the resulting String.

Let’s take an example:

Float givenFloatvar = 2.25f;
String res = new DecimalFormat("#.0000").format(givenFloatvar);
assertEquals("2.2500", res);

💥If there is no fractional part after we apply the formatting, DecimalFormat will return the whole number:

Float givenFloatvar = 1.0025f;
String res = new DecimalFormat("#.##").format(givenFloatvar);
assertEquals("1", res);

💥If we pass null as an argument, we will get the IllegalArgumentException:

Float givenFloatvar = null;
assertThrows(IllegalArgumentException.class, () -> new DecimalFormat("#.000").format(givenFloatvar));

Check out this article - C++ String Concatenation and Swap Function in Java and Hashcode Method in Java.

 

Frequently Asked Questions

What are a string and a float?

Strings can be letters, numbers (without values), or anything else. It's basically just text. Floats are numbers with a decimal point. eg: 3.676873489,36.0.

What is a concat function in Java?

The concat() method basically appends a string at the end of some other string.

How do you link two strings in Java?

In Java, we can concatenate two strings by using the ‘+’ or ‘+=’ operator, or through the concat() method also, usually defined in java. lang.

Can we add two strings in Java?

To add a character to a String at the specified position, use the StringBuffer class method insert(). This method inserts the string representation of the given data type into StringBuffer at the fixed position.

Conclusion

In this article, we looked at various methods for converting String instances to Float instances and back.

String concatenation and Float.toString() are preferable options for converting to String for simple conversions. If we need more complex formatting, DecimalFormat is the tool to use. If we need a float primitive, we can use Float.parseFloat(), otherwise we can use Float.valueOf() to convert strings to floating-point values. Similarly, DecimalFormat is the best option for custom formatting.

Also, check out these exciting courses from coding ninjas to expand your knowledge, Coding CourseCode StudioInterview ExperienceGuided PathInterview ProblemsTest SeriesLibrary, and Resources

Want To Learn More About brand-new technologies? We Have A Whole Category, visit Coding Ninjas and Coding Ninjas Studio to find courses and content related to Data Structures!

Happy Learning!

Live masterclass