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 OverflowYou 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
Try this pattern:
\d+(?:\.\d+)?
Edit:
\d+ match 1 or more digit
(?: non capturing group (optional)
\. '.' character
\d+ 1 or more digit
)? Close non capturing group
Considering the input "114.8 43801", you would want to use a white space as your delimiter. By using '\D+' as your delimiter, your split the string at any non digit as per the Java documentation: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Hence, you are splitting at the dot of '114.8'.
Try to use the default whitespace delimiter (Do no set one..) and it should work.
You should use regular expressions. docs for Pattern
String raw="Orville's Acres, 114.8 43801";
Pattern p=Pattern.compile("\\d+.?[\\d]*");
Matcher m=p.matcher(raw);
while(m.find()){
System.out.println(m.group());
}
Output:
114.8
43801
regex - Java - Split String to get decimal number - Stack Overflow
Convert string to decimal number with 2 decimal places in Java - Stack Overflow
java - How to extract fractional digits of double/BigDecimal - Stack Overflow
Java: transform decimal number to String - Stack Overflow
Assuming that there may be no dot (.) between the string transaction number and the number you're searching for, use
Pattern regex = Pattern.compile("(?i)transaction number [^.]*\\b(\\d+)\\.");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group(1);
}
Explanation:
(?i) # case insensitive matching mode
transaction\ number # Match this literal text
[^.]* # Match any number of characters except dots
\b # Match the position at the start of a number
(\d+) # Match a number (1 digit or more), capture the result in group 1
\. # Match a dot
If you simply want to find the very first number after transaction number, then use
Pattern.compile("(?i)transaction number\\D*(\\d+)")
\D matches any character that is not a digit.
try this
s = s.replaceAll(".* is (\\d+).*", "$1");
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
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
...
*/
This line is your problem:
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code
import java.text.DecimalFormat;
String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);
And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.
Java convert a String to decimal:
String dennis = "0.00000008880000";
double f = Double.parseDouble(dennis);
System.out.println(f);
System.out.println(String.format("%.7f", f));
System.out.println(String.format("%.9f", new BigDecimal(f)));
System.out.println(String.format("%.35f", new BigDecimal(f)));
System.out.println(String.format("%.2f", new BigDecimal(f)));
This prints:
8.88E-8
0.0000001
0.000000089
0.00000008880000000000000106383001366
0.00
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.
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);