Languages
[Edit]
EN

Java - convert String to float

7 points
Created by:
Violet-Hoffman
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

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join