Reputation: 2721
I'm trying to write a regular expression to match both positive and negative floating points of any length of characters. I tried this
/^-|[0-9\ ]+$/
However this is still wrong because for example it would match "46.0" and "-46.0" but will also match "4-6.0" which I don't want.
At the moment i'm using this
/^-|[0-9][0-9\ ]+$/
This fixes the first problem but this will match something like "-4g" and that is also incorrect.
What expression can I use to match negative and positive floating points?
Upvotes: 2
Views: 11926
Reputation: 77
Try this...
I am sure, it's work in javascript.
var pattern = new RegExp("^-?[0-9.]*$");
if (pattern.test(valueToValidate)) {
return true;
} else {
return false;
}
Upvotes: -1
Reputation: 10107
Well mine is bit lesser, optional you can remove {1,3}
limits to minimum 1 and max 3 numbers part and replace that with +
to make no limit on numbers.
/^[\-]?\d{1,3}\.\d$/
Upvotes: -1
Reputation: 324840
/^[-+]?[0-9]+(?:\.[0-9]+)?(?:[eE][-+][0-9]+)?$/
This also allows for an exponent part. If you don't want that, just use
/^[-+]?[0-9]+(?:\.[0-9]+)?$/
Hope this helps.
Upvotes: 0
Reputation: 112927
Why not the following?
parseFloat(x) === x
If you really want a regex, there are entire pages on the internet dedicated to this task. Their conclusion:
/^[-+]?[0-9]*\.?[0-9]+$/
or
/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
if you want to allow exponential notation.
Upvotes: 7