How do I include negative decimal numbers in this regular expression?
You should add an optional hyphen at the beginning by adding -?
(?
is a quantifier meaning one or zero occurrences):
^-?[0-9]\d*(\.\d+)?$
I verified it in Rubular with these values:
10.00
-10.00
and both matched as expected.
let r = new RegExp(/^-?[0-9]\d*(\.\d+)?$/);
//true
console.log(r.test('10'));
console.log(r.test('10.0'));
console.log(r.test('-10'));
console.log(r.test('-10.0'));
//false
console.log(r.test('--10'));
console.log(r.test('10-'));
console.log(r.test('1-0'));
console.log(r.test('10.-'));
console.log(r.test('10..0'));
console.log(r.test('10.0.1'));
Some Regular expression examples:
Positive Integers:
^\d+$
Negative Integers:
^-\d+$
Integer:
^-?\d+$
Positive Number:
^\d*\.?\d+$
Negative Number:
^-\d*\.?\d+$
Positive Number or Negative Number:
^-?\d*\.{0,1}\d+$
Phone number:
^\+?[\d\s]{3,}$
Phone with code:
^\+?[\d\s]+\(?[\d\s]{10,}$
Year 1900-2099:
^(19|20)[\d]{2,2}$
Date (dd mm yyyy, d/m/yyyy, etc.):
^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$
IP v4:
^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$
I don't know why you need that first [0-9]
.
Try:
^-?\d*(\.\d+)?$
Update
If you want to be sure that you'll have a digit on the ones place, then use
^-?\d+(\.\d+)?$
UPDATED(13/08/2014): This is the best code for positive and negative numbers =)
(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}
I tried with this numbers and works fine:
-1234454.3435
-98.99
-12.9
-12.34
-10.001
-3
-0.001
-000
-0.00
0
0.00
00000001.1
0.01
1201.0000001
1234454.3435
7638.98701
This will allow a -
or +
character only when followed by a number:
^([+-](?=\.?\d))?(\d+)?(\.\d+)?$