Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression for negative Numbers with decimal

I want to test for this input: [an optional negative sign] 2 digits [an optional . and an optional digit] like this:

-34 or -34.5333 or 34.53333 or 34 in JavaScript

This is what I came up with but it doesn't work!

/^(-)\d{2}(\.d\{1})$/

Can someone please help me?

like image 676
Manikandan Thangaraj Avatar asked Oct 13 '11 04:10

Manikandan Thangaraj


People also ask

How do you handle negative numbers in JavaScript?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

Does decimal allow negative number?

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.

How do you define a negative number in JavaScript?

Definition and Usage The Math. sign() method retuns whether a number is negative, positive or zero. If the number is positive, this method returns 1. If the number is negative, it returns -1.


2 Answers

Try this regex:

/^-?\d{2}(\.\d+)?$/
like image 193
Prince John Wesley Avatar answered Oct 05 '22 18:10

Prince John Wesley


this regex matches any valid integer.

/^0$|^-?[1-9]\d*(\.\d+)?$/

you can modify this to suite your needs :

/^-?[1-9]\d{0,1}(\.[1-9]{1})?$/

this matches 2.1, 21.4, 3, 90...

like image 31
gion_13 Avatar answered Oct 05 '22 17:10

gion_13