2

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?

Zeeno
  • 2,671
  • 9
  • 37
  • 60

4 Answers4

7

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.

Domenic
  • 110,262
  • 41
  • 219
  • 271
-1

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$/
STEEL
  • 8,955
  • 9
  • 67
  • 89
-1

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;

}

  • Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. In particular, does it accept `3.4.5`? (It shouldn't) How about the empty string? – Toby Speight Jun 08 '17 at 11:30
-1
/^[-+]?[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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592