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'));

Leave a Comment