Ricky
Ricky

Reputation: 7889

RegEx for decimal number with maximum length ignoring dot

I am after a regex that allows a number to be a maximum length with decimal places.

It should allow 16 numbers maximum and 3 decimal places, however the 16 max should include the decimals but not the . character. I've tried and have this so far: ^(?=^[\d\.].{0,16}$)[0-9]+(\.[0-9]{1,3})?$, which is close except it allows 17 single numbers, when it should only accept 16. If I change {0,16} to {0,15} it then breaks the decimals.

Accepted values:

Rejected:

Thanks in advance.

Upvotes: 0

Views: 1901

Answers (1)

anubhava
anubhava

Reputation: 785176

Your regex is fairly close, you may use this regex:

^(?=(?:\d\.?){0,16}$)\d+(?:\.\d{1,3})?$

RegEx Demo

RegEx Details:

  • (?=(?:\d\.?){0,16}$): is positive lookahead to assert that we have 0 to 16 digits in input where dot is optional.
  • \d+(?:\.\d{1,3})?: Match an integer or a decimal number with 1 to 3 digits.

Upvotes: 5

Related Questions