You don't need to have a separate patterns for integer and floating point numbers. Just make the decimal part as optional and you could get both type of numbers from a single group.

(\d+(?:\.\d+)?)

Use the above pattern and get the numbers from group index 1.

DEMO

Code:

String s = "Oats     124   0.99        V    1.65";
Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
 Matcher matcher = regex.matcher(s);
 while(matcher.find()){
        System.out.println(matcher.group(1));
}

Output:

124
0.99
1.65

Pattern explanation:

  • () capturing group .
  • \d+ matches one or more digits.
  • (?:) Non-capturing group.
  • (?:\.\d+)? Matches a dot and the following one or more digits. ? after the non-capturing group makes the whole non-capturing group as optional.

OR

Your regex will also work only if you change the order of the patterns.

(\d+\.\d+|\d+)

DEMO

Answer from Avinash Raj on Stack Overflow
Discussions

regex - Java - Split String to get decimal number - Stack Overflow
I need to extract some data from an website and then save some values in variables. Here you've got the code: public class Principal { public static void main(String[] args) throws IOException ... More on stackoverflow.com
🌐 stackoverflow.com
November 17, 2015
Convert string to decimal number with 2 decimal places in Java - Stack Overflow
In Java, I am trying to parse a string of format "###.##" to a float. The string should always have 2 decimal places. Even if the String has value 123.00, the float should also be 123.00, not 123... More on stackoverflow.com
🌐 stackoverflow.com
java - How to extract fractional digits of double/BigDecimal - Stack Overflow
Say we have a double value of 12345.6789 (should be dynamic) Now the requirement is split the number and get the decimal digits and fractional digits, which would be: double number = 12345.6789; ... More on stackoverflow.com
🌐 stackoverflow.com
July 16, 2012
How to convert string to decimal in Java - Stack Overflow
But that string isn't a number, so java cannot convert it. I do nut have much experience with RandomAccessFiles, but why don't you use a BufferedWriter with a simple FileWriter? ... When you give String.format("x",...), you are telling the compiler to give you a Hexadecimal number. But then you are trying to parse it as a decimal ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
CodingTechRoom
codingtechroom.com › question › extract-integers-decimals-string-java
How to Use Regex for Extracting Integers or Decimals from a String in Java? - CodingTechRoom
Failing to account for edge cases such as negative numbers or formats with commas. Use the regex pattern `[-]?\d*\.?\d+` to capture integers and decimals. Make sure to use `Pattern` and `Matcher` classes in Java for regex operations. Test your regex string against various sample strings to ensure it captures all desired formats.
🌐
Quora
quora.com › How-do-you-extract-numbers-from-a-string-in-Java
How to extract numbers from a string in Java - Quora
Answer (1 of 3): You can extract numbers from a string in Java using two methods. Method 1: Using the in-built method Character.isDigit() The Character.isDigit() method determines whether the character is a digit or not. So you traverse the string, get each character one by one and check if it ...
🌐
CodeProject
codeproject.com › Questions › 277738 › Extracting-double-decimal-number-from-string
[Solved] Extracting double/decimal number from string
November 4, 2011 - Aviso legal: las referencias a una empresa, producto o servicios específicos en este Sitio no están controladas por GoDaddy.com LLC y no constituyen ni implican la asociación ni respaldo a anunciantes externos
🌐
Baeldung
baeldung.com › home › java › java string › find all numbers in a string in java
Find All Numbers in a String in Java | Baeldung
June 24, 2025 - List<String> decimalNumsFound = findDecimalNums("x7854.455xxxxxxxxxxxx-3x-553.00x53xxxxxxxxxxxxx3456xxxxxxxx3567.4xxxxx"); assertThat(decimalNumsFound) .containsExactly("7854.455", "-3", "-553.00", "53", "3456", "3567.4"); We may also wish to convert the found numbers into their Java types.
Find elsewhere
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 311036 › want-to-print-number-after-decimal-point
java - want to print number after decimal point [SOLVED] | DaniWeb
September 14, 2010 - Okay, doing it your way, what happens if there are two numbers that you want to extract the decimal parts of? ... import javax.swing.*; import java.text.*; class Demo { public static void main (String[] args){ DecimalFormat twoDigit= new DecimalFormat("0.00"); // rounds num to twodigits int j=0; double x=0.0; double[] I= new double[4]; int[] DD= new int[4]; while(j<=2) // loop to enter more than one decimal num { String enter=JOptionPane.showInputDialog("enter num"); double i=Double.parseDouble(enter); double z=i; int dd=(int)z; // taken z as int as temporaly storage to get integeral part of n
Top answer
1 of 2
2

You can try following regex:

(?:class="priceValue">\s*)(\d*\.\d+)

It looks for a class="priceValue"string followed by a price

Here is DEMO and explanation

2 of 2
2

I know you are asking for regex, but consider making your life easier by parsing the HTML as if it was a structured XML document it is rather than a normal string. There are libraries that would handle this for you, and stop you from worrying about text formatting, legal linebreaks and other stuff:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.7.1</version>
</dependency>

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class HtmlParser {
    public static void main(String[] args) {

        Document doc;
        try {
            doc = Jsoup.connect("http://www.numbeo.com/cost-of-living/country_result.jsp?country=Turkey").get();
            Elements rows = doc.select("table.data_wide_table tr.tr_standard"); // CSS selector to find all table rows
            for (Element row : rows) {
                System.out.println("Item name: " + row.child(0).text()); // Milk will be here somewhere
                System.out.println("  Item price by column number: " + row.child(1).text());
                System.out.println("  Item price by column class:  " + row.getElementsByAttributeValue("class", "priceValue").get(0).text());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 Output:
 Item name: Meal, Inexpensive Restaurant
   Item price by column number: 15.00 TL
   Item price by column class: 15.00 TL
 Item name: McMeal at McDonalds (or Equivalent Combo Meal)
  Item price by column number: 15.00 TL
  Item price by column class: 15.00 TL
...
*/
🌐
Baeldung
baeldung.com › home › java › java string › retain only digits and decimal separator in string
Retain Only Digits and Decimal Separator in String | Baeldung
January 18, 2024 - Let’s suppose we need to remove ... from a String that contains alphanumeric and special characters while leaving the decimal separator in place. For instance, we want to extract the numeric and decimal part of the text from “The price of this bag is 100.5$” to get just “100.5”, which is the price part. In this tutorial, we’ll explore four distinct approaches for doing so in Java...
Top answer
1 of 4
50
double number = 12345.6789; // you have this
int decimal = (int) number; // you have 12345
double fractional = number - decimal // you have 0.6789

The problem here is that the fractional part is not written in memory as "0.6789", but may have certain "offsets", so to say. For example 0.6789 can be stored as 0.67889999291293929991.

I think your main concern here isn't getting the fractional part, but getting the fractional part with a certain precision.

If you'd like to get the exact values you assigned it to, you may want to consider this (altho, it's not a clean solution):

String doubleAsText = "12345.6789";
double number = Double.parseDouble(doubleAsText);
int decimal = Integer.parseInt(doubleAsText.split("\.")[0]);
int fractional = Integer.parseInt(doubleAsText.split("\.")[1]);

But, as I said, this is not the most efficient and cleanest solution.

2 of 4
11

You can't do what you want to do in an exact way.

One problem is if you have the number 1.05 what should the result be?

double number = 1.05;
int decimal = 1;
int fractional = 5; // Oops! "1.05" and "1.5" give the same result.

How about this?

int fractional = 05; // Still not correct. This is an octal number.

Another problem is that the double type can't exactly represent 12345.6789. It stores a slightly different number instead. This is called representation error. So the fractional part won't actually be 6789. Instead you can round it off to some number of decimal places.

int fractional = (int)Math.round((number - decimal) * 1000);
🌐
javaspring
javaspring.net › blog › how-to-extract-numeric-values-from-input-string-in-java
How to Extract Numeric Values from a String in Java: Tutorial with Examples — javaspring.net
Pros: Handles complex cases (decimals, signs, multiple numbers). Cons: Regex can be overkill for simple tasks; may require tuning for edge cases (e.g., locale-specific decimals like "19,99" in Europe). StringTokenizer splits strings into tokens using delimiters. Use non-digit delimiters to isolate numeric tokens. import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; public class StringTokenizerExample { public static List<String> extractNumbersWithTokenizer(String input) { List<String> numbers = new ArrayList<>(); // Split on non-digit characters (delimiters: [^0
🌐
javathinking
javathinking.com › blog › convert-text-to-decimal-java
Converting Text to Decimal in Java — javathinking.com
Double.parseDouble(String s): Similar to Float.parseFloat, but it returns a double value. new BigDecimal(String val): This constructor creates a BigDecimal object from the given string representation of a decimal number.
🌐
Coderanch
coderanch.com › t › 504515 › java › decimal
get decimal value (Beginning Java forum at Coderanch)
July 28, 2010 - One way is to put the float value ... integer from the float to get the fractional part. ... this topic may be useful too: https://coderanch.com/t/392641/java/java/decimal-part-float you could also get it as float rest=number%1. ... And then just multiply by 10^(number of digits) and round. So to get 3 digits: Another way that will always return you all decimals is using Strings: This will ...
🌐
CodeSpeedy
codespeedy.com › home › extract digits from a string in java
Extract Digits from a String in Java - CodeSpeedy
December 13, 2019 - package program; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String "); String inp = new String(); inp = sc.nextLine(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(inp); while(m.find()) { System.out.println("The digits extracted "+m.group()+" "); System.out.print(" "); } } }
🌐
Attacomsian
attacomsian.com › blog › java-extract-digits-from-string
How to extract digits from a string in Java
February 22, 2020 - The following example shows how you can use the replaceAll() method to extract all digits from a string in Java: // string contains numbers String str = "The price of the book is $49"; // extract digits only from strings String numberOnly = ...
🌐
Baeldung
baeldung.com › home › java › java string › converting string to bigdecimal in java
Converting String to BigDecimal in Java | Baeldung
June 17, 2026 - The DecimalFormat.parse method returns a Number, which we convert to a BigDecimal number using the setParseBigDecimal(true). Usually, the DecimalFormat is more advanced than we require. Thus, we should favor the new BigDecimal(String) or the BigDecimal.valueOf() instead. Java provides generic exceptions for handling invalid numeric Strings.