Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - convert String to float

7 points
Created by:
652

In Java, we can convert String to float in couple of different ways.

Short solutions:

``````// solution 1
float num1 = Float.parseFloat("123.45");

// solution 2
Float num2 = Float.valueOf("123.45");

// solution 3
Float num3 = new Float("123.45");``````

## 1. Using Float.parseFloat()

``````public class Example1 {

public static void main(String[] args) {
String str = "123.45";
float num = Float.parseFloat(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 2. Using Float.valueOf()

``````public class Example2 {

public static void main(String[] args) {
String str = "123.45";
Float num = Float.valueOf(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 3. Using constructor - new Float(String s)

``````public class Example3 {

public static void main(String[] args) {
String str = "123.45";
Float num = new Float(str);
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

## 4. Using DecimalFormat parse method

``````import java.text.DecimalFormat;
import java.text.ParseException;

public class Example4 {

public static void main(String[] args) throws ParseException {
String str = "123.45";
float num = DecimalFormat.getNumberInstance().parse(str).floatValue();
System.out.println(num); // 123.45
}
}``````

Output:

``123.45``

Join to our subscribers to be up to date with content, news and offers.