I need some regex that will match only numbers that are decimal to two places. For example:
^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
var regexp = /^[0-9]*(\.[0-9]{0,2})?$/;
//returns true
regexp.test('10.50')
//returns false
regexp.test('-120')
//returns true
regexp.test('120.35')
//returns true
regexp.test('120')
It depends a bit on what shouldn't match and what should and in what context
for example should the text you test against only hold the number? in that case you could do this:
/^[0-9]+\.[0-9]{2}$/
but that will test the entire string and thus fail if the match should be done as part of a greater whole
if it needs to be inside a longer styring you could do
/[0-9]+\.[0-9]{2}[^0-9]/
but that will fail if the string is is only the number (since it will require a none-digit to follow the number)
if you need to be able to cover both cases you could use the following:
/^[0-9]+\.[0-9]{2}$|[0-9]+\.[0-9]{2}[^0-9]/
If you're looking for an entire line match I'd go with Paul's answer.
If you're looking to match a number witihn a line try: \d+\.\d\d(?!\d)
\d+
One of more digits (same as [0-9]
) \.
Matches to period character \d\d
Matches the two decimal places (?!\d)
Is a negative lookahead that ensure the next character is not a digit.You can also try Regular Expression
^\d+(\.\d{1,2})?$
or
var regexp = /^\d+\.\d{0,2}$/;
// returns true
regexp.test('10.5')
or
[0-9]{2}.[0-9]{2}
or
^[0-9]\d{0,9}(\.\d{1,3})?%?$
or
^\d{1,3}(\.\d{0,2})?$