Pavel F
Pavel F

Reputation: 760

Regular expression for positive decimal number with 0, 1 or 2 decimal places

Please help me make regular expression for positive decimal number with 0, 1 or 2 decimal places. It must allow comma and dot. For example it must allow:

0,01
0.01
0,1
1
1.1
1,11

but not allow:

-1
0.0
0,00
.01
0
1,111
1.111

I have this /(^\d*(?:\.|\,)?\d*[1-9]+\d*$)|(^[1-9]+\d*(?:\.|\,)\d*$)/ but I can`t find how to disallow more than 2 decimal places.

UPDATE I must reject 0.0, 0 and etc.

Upvotes: 4

Views: 15417

Answers (5)

Nicholas Carey
Nicholas Carey

Reputation: 74267

This will do what you want.

I've added whitespace and comments and parentheses to clarify it:

(                   #
  ( 0*[1-9]\d*   )  # a non-zero integer portion, followed by
  ( [\.,]\d{1,2} )? # an optional fraction of 1 or 2 decimal digits
)                   # 
|                   # OR
(                   #
  ( 0+ )            # a zero integer portion, followed by
  (                 # an mandatory non-zero 1-2 digit fraction, consisting of
    [\.,]           # a decimal point
    (               # followed by 
      ( 0[1-9]   )  # a 0 followed by a 1-9,
      |             # OR
      ( [1-9]\d? )  # a 1-9 followed by an optional decimal digit
  )
)

The regular expression is suboptimal it something like 0000000000.01 will backtrack when it doesn't find a non-zero digit following the zeros in the integer portion, but it should work.

Upvotes: 1

agent-j
agent-j

Reputation: 27913

Edit 2: now disallows exactly 0,0.0, etc.

This matches at least one digit before the decimal place, followed by an optional decimal place, followed by 0-2 digits.

The negative lookahead looks for any flavor of absolute zero and prevents a match.

^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$

This is the raw regex, so you'll need to escape it appropriately for your language. (For example, in some languages you need to double the \ slashes as \\.

/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/

Upvotes: 9

Matt Ball
Matt Ball

Reputation: 359826

What you've got so far seems unnecessarily complicated to me. How about just

/^\d+([.,]\d{0,2})?$/

This is correct for every test case in the OP except for:

0.0
0,00
0

I don't see why you'd reject these.

Upvotes: 3

bw_üezi
bw_üezi

Reputation: 4564

/^\d+([.,]\d{1,2})?$/

this will properly disallow these "unformatted" numbers .01, 3., etc.

if we have zero decimal place digits we probably as well don't want the decimal separator.

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

you can use the bracket notion to limit the number of digits:

\d{0,2} would mean any run of digits from a minimum of 0 to a maximum of 2

Upvotes: 1

Related Questions