How to extract float numbers from a string in Java

In this tutorial, we will look at how to extract float numbers from a string in Java. To do this we will use a regular expression to match and find float values in a string.

Extract float numbers from a string in Java

We will use pattern matching to find float numbers from the string. Given below is the pattern that you can use. This pattern can identify negative float numbers too.

"[-]?[0-9]*\\.?[0-9]+"

Next, we have to match it with the input string which can be done using the matcher class. Then, using the find() method and the group() method we group and store the float numbers.

The following program uses the above methods and gives us our required output.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FloatFromString {
  public static void main(String args[]) {
    //input string
    String s = "Your total bill ammount is 1243.45 Rs.";
    float flt = 0;
    //Creating a pattern to identify floats
    Pattern pat = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
    //matching the string with the pattern
    Matcher m = pat.matcher(s);
    //extracting and storing the float values
    while(m.find()) {
      flt = Float.parseFloat(m.group());
    }
    //printing the float values
    System.out.println("The float value from the string is:");
                System.out.println(flt);
  }
}

Output:

The float value from the string is:
1243.45

The above program can be modified to extract multiple float values from the string using ArrayList. This is shown in the program below.

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FloatFromString {
  public static void main(String args[]) {
    //input string
    String s = "Your total bill ammount is 1243.45 Rs. and tax to be paid is 45.65 Rs.";
    //ArrayList to store the output
    ArrayList<Float> f = new ArrayList<Float>();
    //Creating a pattern to identify floats
    Pattern pat = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
    //matching the string with the pattern
    Matcher m = pat.matcher(s);
    //extracting and storing the float values
    while(m.find()) {
      f.add(Float.parseFloat(m.group()));
    }
    //printing the float values
    System.out.println("The float values from the string are:");
    for(int i =0; i<f.size(); i++) {
      System.out.println(f.get(i));
    }
  }
}

Output:

The float values from the string are:
1243.45
45.65

Here is a tutorial that you can check out next: Remove leading and trailing spaces from a string in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *