Leo Messi
Leo Messi

Reputation: 6166

Regex with maximum 2 digits after the decimal point

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?

Upvotes: 4

Views: 8392

Answers (2)

The fourth bird
The fourth bird

Reputation: 163267

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}.

Upvotes: 4

Thomas
Thomas

Reputation: 181745

Your regex is saying "some digits, followed by 0-2 occurrences of a dot followed by a digit". Spot the mistake? 3.1.4 would match, but 3.14 wouldn't. Contrary to what you state in the question, 3 digits after the point wouldn't match either.

Instead, you would need something like this, assuming that the fractional part should be optional:

\d+(\.\d{0,2})?

Or, anchored and escaped for a string in your language of choice:

"^\\d+(\\.\\d{0,2})$"

Upvotes: 1

Related Questions