I want to write a regular expression that must take a valid only the numerical values with 0, 1 or 2 digits after the decimal point.
So I tried to do it like: "^\\d+(\\.\\d){0,2}$" but it returns true even for numbers with 3 digits after the decimal point.
Any ideas what's wrong?
Your regex ^\d+(\.\d){0,2}$ matches 1 or 1.0 but also 1.0.0 because you specifiy a quantifier for 0-2 times for the group (\.\d){0,2} and would not match 3 digits after the dot.
To match a digit which could be followed by a dot and 1 or 2 digits after the dot you could use:
^\d+(?:\.\d{1,2})?$
Here the group after the first digit(s) is optional (?:\.\d{1,2})? and the quantifier is specified for the digit \d{1,2}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With