EN
Java - convert String to float
7 points
In Java, we can convert String to float in couple of different ways.
Short solutions:
xxxxxxxxxx
1
// solution 1
2
float num1 = Float.parseFloat("123.45");
3
4
// solution 2
5
Float num2 = Float.valueOf("123.45");
6
7
// solution 3
8
Float num3 = new Float("123.45");
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
float num = Float.parseFloat(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
Float num = Float.valueOf(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
String str = "123.45";
5
Float num = new Float(str);
6
System.out.println(num); // 123.45
7
}
8
}
Output:
xxxxxxxxxx
1
123.45
xxxxxxxxxx
1
import java.text.DecimalFormat;
2
import java.text.ParseException;
3
4
public class Example4 {
5
6
public static void main(String[] args) throws ParseException {
7
String str = "123.45";
8
float num = DecimalFormat.getNumberInstance().parse(str).floatValue();
9
System.out.println(num); // 123.45
10
}
11
}
Output:
xxxxxxxxxx
1
123.45