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,591
  • 7
  • 35
  • 59

4 Answers4

6

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
  • 105,522
  • 40
  • 210
  • 262
-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
  • 7,168
  • 8
  • 62
  • 80
-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
  • 311,322
  • 76
  • 447
  • 566