test
test

Reputation: 43

Regular expression for any double type number

I am trying to do the following:

myVar = q.match(/[0-9]*\.[0-9]+|[0-9]+/);

However, when I type a decimal, myVar doesn't pick up the decimal until after I type decimal values.

Entered 3, myVar = 3
Entered ., myVar = 3
Entered 3, myVar 3.3

How do I modify this so myVar would equal 3. at the second step?

Thanks.

Upvotes: 3

Views: 4506

Answers (2)

Brian Stephens
Brian Stephens

Reputation: 5261

It looks like you also want to match something like .3, right? But you have to be sure your regex doesn't match a decimal point by itself .. So you could do it with these alternations:

myVar = q.match(/\d+\.\d*|\.?\d+/);

\d+\.\d* matches 3., 3.3, 3.33 etc.

\.?\d+ matches .3, .33, 3, 33, etc.

ALTERNATE: If you need to allow commas for thousands, millions, etc., use the following:

myVar = q.match(/\d{1,3}(,\d{3})*\.\d*|\d{1,3}(,\d{3})*|\.\d+/);

\d{1,3}(,\d{3})*\.\d* matches 3., 3.3, 3.33, 3,333.3 etc.

\d{1,3}(,\d{3})* matches 3, 33, 3,333 etc.

\.\d+ matches .3, .33, etc.

Upvotes: 2

brso05
brso05

Reputation: 13222

Don't use the + after [0-9] it means 1 or more occurrence. Try using *. It should work.

myVar = q.match(/[0-9]*\.[0-9]*|[0-9]*/);

Can be simplified to:

myVar = q.match(/[0-9]*\.[0-9]*/);

Problem is it is looking for atleast 1 number after the . In your case you want 0 or more.

Upvotes: 1

Related Questions