32

I need some regex that will match only numbers that are decimal to two places. For example:

  • 123 = No match
  • 12.123 = No match
  • 12.34 = Match
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
geoffs3310
  • 13,640
  • 23
  • 64
  • 85

5 Answers5

47
^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
Paul
  • 2,972
  • 2
  • 21
  • 16
28
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')
Chetan Buddh
  • 452
  • 8
  • 14
  • 2
    Did you read the question They don't want to match integer. And they want to match exactly 2 decimal. – Toto Sep 15 '18 at 09:50
10

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.
moinudin
  • 134,091
  • 45
  • 190
  • 216
Grhm
  • 6,726
  • 4
  • 40
  • 64
5

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]/
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • Interesting approach. I'm not sure it would happen a number at the end of a longer string. I'd suggest your last line could be changed to `/[0-9]+\.[0-9]{2}([^0-9]|$)/` – Grhm Jan 14 '11 at 13:09
2

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})?$
Kailas
  • 3,173
  • 5
  • 42
  • 52