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
A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.
If UNSIGNED is used with DECIMAL , negative values are not allowed. MySQL stores numbers in DECIMAL columns as strings. Therefore, numbers outside the maximum numeric range for this data type may be stored in a DECIMAL column.
The decimal datatype can store negative numbers as well. So to answer your question, yes you can use the decimal datatype to store negative decimal numbers.
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With