Ciupaz
Ciupaz

Reputation: 699

Regular Expression for decimal numbers (at max 3 decimal numbers with comma)

How can I write a regular expression that validates an input text box that should contain only decimal values? The value can have at max 3 decimals (but also none) with comma as the separator.

For example, these values given below are valid:-

1,234
1,23
1,2
1

These are not valid:

1,2345 (too many decimal numbers)
A (a letter is not a number)
  (a space or string empty)
1.234 (used a dot instead of a comma)

Upvotes: 2

Views: 3200

Answers (4)

vroomfondel
vroomfondel

Reputation: 3106

Note if you only want one character before the decimal, remove the +

^\d+(,(\d?){3})?$


^   //start
\d+   //one or more decimal digits
(,(\d?){3})?    //a comma, followed by up to 3 decimal digits, optionally
$    //end

If you don't want 1, to be accepted, then the middle section can be (,\d(\d?){2})?

Upvotes: 1

Gabe
Gabe

Reputation: 86728

How about @"\d+,?\d{0,3}": 1 or more digits, then an optional comma, then 0 to 3 more digits. This assumes that you allow any number of digits before the comma. In your examples you only have one, in which case you would want to remove the +.

If the value 1, is not valid, you'll have to move the ? to the end: @"\d+(,\d{1,3})?"

Upvotes: 2

You could use a pattern like this:

[0-9]+(,[0-9]{1,3})?

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

Try something like this:

\d+(?:,\d{1,3})?

Explained:-

\d+        # multiple digits
(?:        # start non-capturing group  
  ,        # a comma
  \d{1,3}  # 1-3 digits
)?         # end non-capturing group, made optional

Upvotes: 7

Related Questions