Languages
[Edit]
EN

Java - convert String to float

7 points
Created by:
Marcin
2447

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

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.