How do I match negative numbers as well by this regular expression? This regex works fine with positive values, but I want it to also allow negative values e.g. -10, -125.5 etc.
^[0-9]\d*(\.\d+)?$
Thanks
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'));