Languages
[Edit]
EN

Java - convert String to float

7 points
Created by:
Marcin
15710

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

 

Java - String conversion

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join