Zeeno
Zeeno

Reputation: 2721

Javascript: Regular expression to allow negative and positive floating point numbers?

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

Answers (4)

user3414092
user3414092

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

STEEL
STEEL

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

Niet the Dark Absol
Niet the Dark Absol

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

Domenic
Domenic

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

Related Questions