Reputation: 449
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
Reputation: 1013
this works for me
string="some text with the number -123456.789 in it";
alert(string.replace(/[^-\d+.]/g,''));
Upvotes: 1
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
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
Reputation: 324610
Here is a regex for decimal numbers:
/^-?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/
To break it down:
Upvotes: 0