×

How to Convert String to float in Java

How to Convert String to Float in java

It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float in the following ways:

  • Convert using Float.parseFloat() method
  • Convert using Float.valueOf() method
  • Convert using constructor new Float(String).floatValue()

Convert using Float.parseFloat()

The parseFloat() is the static method of Float class parses the String argument and returns a float value. The value that method returns is not an instance of Float class; it just a primitive float value. This is the most common and popular method to convert String to float. The signature of the parseFloat() method is given below:

public static int parseFloat(String s)

The parameter s will be converted to a primitive float value.

Example

In the following example, str is a variable of type String having value “89.67”. f is a variable of float type that stores the converted value of str. Float is a wrapper class. The parseFloat() is a static method passing str as an argument to it and returns float value. The println statement prints the converted value of str.

public class StringToFloatExample
{ 
public static void main(String args[])
{ 
String str="89.67"; 
float f=Float.parseFloat(str); 
System.out.println("After conversion float value is: " +f);
}
}

Output

After conversion float value is: 89.67

Remember: All characters must be in digits; the number can have a minus sign.

Valid Conversion

  • String number=”-23.67”;
  • String number=”23.67”;

Invalid Conversion

  • String number=”369.90a”;
  • String number=” a 369.90”;

If you defines a String as above, Float.parseFloat() throws “NumberFormatException,” because it is not a valid conversion. 

Convert using Float.valueOf() method

The Float.valueOf() is a static method that returns a Float object holding the value of the specified String. The value that method returns is an instance of Float class not a primitive type. The signature of the method is given below-

public static Float valueOf(String s)

Example

Consider the example, avg is a variable of type String having value “225.92”. num is a variable of float type that stores the converted value of str. Float is a wrapper class. The Float.valueOf() is a static method passing avgas an argument to it and returns a float value. The println statement prints the converted value of num.

public class StringToFloatExample1
{ 
public static void main(String args[])
{
String avg = "225.92";
float num= Float.valueOf(avg);
System.out.println("converted  value of avg is: " + num);
}
}

Output

After conversion value of avg is: 225.92

Convert using constructor new Float(String).floatValue()

It is an alternative method is to create an instance of Float class and then invoke it's floatValue() method. You can create constructor in the following ways:

String str= "67.34";
Float floatObject = new Float(str);
float value= floatObject.floatValue();

You can also write above code as: 

String str = "67.34";

float value = new Float(str).floatValue();

Or

float value = new Float("67.43").floatValue();

Example 

Consider the example, val is a variable of type String having value “876.234”. num is a variable of float type that stores the converted value of val. The new is a keyword that creates the constructor of the Float class. It has a val as an argument passing to it. It invokes the float.value() method of the Float class. The println statement prints the converted value of num.

public class StringToFloatExample2
{ 
public static void main(String args[])
{
String val= "876.234";
float num = new Float(val).floatValue();
System.out.println("Converted value is: " + num);
}
}

Output

Converted value is: 876.234

Related Topics

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.