maitiest
maitiest

Reputation: 149

RegEx for Both Integer & Float

I need a RegEx to match both Integer values as well as Float numbers. and i want to use it using *Regular Expression Validator *

What should be Valid:

.1

.12

1.2

1.23

12.3

12.34

1

12

What should be Invalid:

.123(this value is having more then 2 decimal values)

1.234(this value is having more then 2 decimal values)

What i exactly want is to take values from 0 to 99.99 only in TextBox(MaxLength=5) Control in ASP.Net with C#.

Upvotes: 1

Views: 9207

Answers (3)

MrHIDEn
MrHIDEn

Reputation: 1879

(^\d{1,2}$)|(^\d{0,2}[.]\d{1,2}$)

(^\d{1,2}$) is for INT
[0 , 1 , 12 , 99]

(^\d{0,2}[.]\d{1,2}$) is for FLOAT
[.1 , .12 , 1.2 , 1.23 , 12.3 , 12.34 , .99 , 99.99]

Upvotes: 0

aelor
aelor

Reputation: 11116

you want a regex like this

^(?:\d{1,2})?(?:\.\d{1,2})?$

here the non capturing group (?:\d{1,2}) will check for values between 0 - 99. this has been made optional with ? because values like .12 , .2 are permitted.

demo here : http://regex101.com/r/oW7rF4

Upvotes: 2

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

You can implement a check like this:

String string = "1.23";

if( 
  string.match(/^\d+$/) || // for "123", "456"
  string.match(/^\d+\.\d{1,2}$/) || // for "123.45", "4.5"
  string.match(/^\.\d{1,2}$/) )  // for ".45", ".8"
    // do something
else 
     // do something else

Note: This is a pseudo-code (or whatever you call it), you can convert it to your language.

Upvotes: 0

Related Questions