Stephen L
Stephen L

Reputation: 351

Regular expression in C# for Number with Decimal Point & Commas

I need to enter amount in a textbox which allows numbers with decimal point and commas. What is the regular expression for this?

I used the below

txtInitialAmountGuarDetails.ValidationSettings.RegularExpression.ValidationExpression = @"^[-+]?\d*[0-9](|.\d*[0-9])(|,\d*[0-9])?$";

But it not working for large numbers like 300,000,000,000,000.

Upvotes: 0

Views: 5869

Answers (5)

NeverHopeless
NeverHopeless

Reputation: 11233

You can try this regex too:

^([+-]?\d{1,3}(?:,\d{1,3})*(?:\.\d+)*)$

Keep in mind . has a specific meaning in regex engine so it is necessary to escape it.

I would also suggest you to not use regex for this task instead look at masked textbox.

Upvotes: 1

Eric Jablow
Eric Jablow

Reputation: 7899

Build it up piecemeal. Given a US locale, a number with these rules has in order:

  • The string beginning: ^
  • An optional sign: [+-]?
  • Up to 3 digits: \d{1,3}
  • A comma followed by 3 digits, repeated any number of times: (?:,\d{3})*
  • An optional decimal point and decimal part: (?:[.]\d+)?
  • The string end: $

Do you have restrictions on the number of digits after the decimal point? Then change the last plus sign to {2} for 2 digits.

So, the regex is:

@"^[+-]?\d{1,3}(?:,\d{3})*(?:[.]\d+)?$"

Or, if you want to explain your work, use the x option and:

@"(?x)            # Extended format.
  ^[+-]?          # Optional sign.
  \d{1,3}         # Initial 1-3 digits.
  (?:,\d{3})*     # Any number of commas followed by 3 digits.
  (?:[.]\d+)?$"   # An optional decimal point followed by any number of digits.

But does C# have a locale-dependent validator already?

Upvotes: 7

Desolator
Desolator

Reputation: 22759

try this one:

^([0-9]{3}[,.]|)+[0-9]{0,3}$

let me know if it needs any enhancements...

Upvotes: -1

This works: \d{1,3}(,\d{3})*\.{0,1}(\d{3},)*\d{0,3}

As for the after the comma issue, any choice should be fine. If you go with commas, my regex works. If you do 5 digits then a space just replace the end with (\d{5}\s{1})*\d{0,5}. And ofcourse if you just dont use any deliminator after the decimal you just put \d*

Upvotes: 1

Deepak Saralaya
Deepak Saralaya

Reputation: 457

I have not run it, but you can try it out.

var regexp =/^\s*?([\d\,]+(\.\d{1,2})?|\.\d{1,2})\s*$/;

Upvotes: 1

Related Questions