×

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 callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.