10

I got this expression from stackoverflow itself - /^\d+(\.\d{0,9})?$/.

It takes care of:

2
23
23.
25.3
25.4334
0.44

but fails on .23. Can that be added to the above expression, or something that would take care of all of them?

2
  • Do you care about false positives? If not a simple \.? at the beginning will do it. Commented Jun 8, 2011 at 20:58
  • You just need to change the first "+" to "*". Plus sign means ONE(1) or more while star means NONE(0) or more. This also doesn't take into account the plus(+) sign or minus(-) sign that can be in front of numbers. That would be "[+-]?" or it might be "[\+\-]?" if they have special meaning inside of the brackets. Then you also have the "e+10" stuff. Commented Mar 3, 2015 at 15:08

3 Answers 3

31

This will capture every case you posted as well as .23

Limit to 9 decimal places

var isDecimal = string.match( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ );

No decimal limits:

var isDecimal = string.match( /^(\d+\.?\d*|\.\d+)$/ );
Sign up to request clarification or add additional context in comments.

9 Comments

Limit the decimal places to nine, and it's perfect.
SyntaxError: Invalid regular expression: /^(\d+\.?\d{0,9}|\.\d{1,9}$/: Unterminated group
@Kooilnc: My bad! I messed it up editing in the decimal limit of 9. Try now
@Ben: yep, but then again it will not capture 3.141592653589793238462643383279502884197169399375105820974 ;~)
@KooiInc - The OP's pattern imposes the 9-decimal-places limit. He doesn't mention the limit specifically, but it looks intentional.
|
2

This covers all your examples, allows negatives, and enforces the 9-digit decimal limit:

/^[+-]?(?=.?\d)\d*(\.\d{0,9})?$/

Live demo: https://regexr.com/4chtk

To break that down:

[+-]?       # Optional plus/minus sign (drop this part if you don't want to allow negatives)
(?=.?\d)    # Must have at least one numeral (not an empty string or just `.`)
\d*         # Optional integer part of any length
(\.\d{0,9}) # Optional decimal part of up to 9 digits

Since both sides of the decimal point are optional, the (?=.?\d) makes sure at least one of them is present. So the number can have an integer part, a decimal part, or both, but not neither.

One thing I want to note is that this pattern allows 23., which was in your example. Personally, I'd call that an invalid number, but it's up to you. If you change your mind on that one, it gets a lot simpler (demo):

/^[+-]?\d*\.?\d{1,9}$/

Comments

1

Try this expression:

^\d*\.?\d*$

1 Comment

It should be ^\d*\.?\d+$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.