Joe
Joe

Reputation: 449

Regex to allow all types of numbers

I just want a field to allow ALL types of numbers: whole, decimal, negative... and all combinations of said types. No commas necessary.

This is the closest I've gotten in about 3 days of fighting with it:

/^[\.\-\d]*?$[1-9][\.\-\d]*?$/

This does not allow whole numbers! I don't undestand what is wrong, can someone please explain how to do this?

Upvotes: 0

Views: 1893

Answers (4)

dt192
dt192

Reputation: 1013

this works for me

string="some text with the number -123456.789 in it";
alert(string.replace(/[^-\d+.]/g,''));

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208405

The following should work:

/^-?\d*\.?\d+$/

Explanation:

^       # start of string anchor
-?      # match a '-', optional
\d*     # match zero or more digits
\.?     # match a '.', optional
\d+     # match one or more digits
$       # end of string anchor

Upvotes: 6

luksch
luksch

Reputation: 11712

Try this:

/^[-+]?\d*\.?\d*$/

Note that this will match "6.", "+5.3", "4" but not "4.4.0"

This is similar to F.J answer, but allow a positively signed input and allows the the number end in a dot ".".

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Here is a regex for decimal numbers:

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

To break it down:

  • From the start of the string...
  • Optionally match a minus sign
  • Either:
    • Match up to three digits
    • Optionally, match any number of (comma followed by three digits) [thousands separators]
  • Or:
    • Match any number of digits [without thousands separators]
  • Optionally match a decimal point followed by any number of digits.
  • Check you've reached the end of the string.

Upvotes: 0

Related Questions