Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp to check if input is only whole numbers (int) , and to check if another is only numbers with 2 decimal places

I want to know what a regex would look like for:

  1. only whole numbers
  2. only numbers with less than or equal to two decimal places (23, 23.3, 23.43)
like image 954
re1man Avatar asked Nov 15 '11 23:11

re1man


1 Answers

Only whole numbers:

/^\d+$/
         # explanation
\d       match a digit
 +       one or more times

Numbers with at most 2 decimal places:

/^\d+(?:\.\d{1,2})?$/

         # explanation
 \d       match a digit...
 +        one or more times
  (        begin group...
   ?:      but do not capture anything
   \.      match literal dot
   \d      match a digit...
   {1,2}   one or two times
  )        end group
 ?        make the entire group optional

Notes:

  • The slashes denote start and end of pattern
  • ^ and $ are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/ matches '398501', but it also matches 'abc123'. The anchors ensures the entire string matches the given pattern.
  • If you want to allow negative numbers, add a -? before the first \d. Again, ? denotes "zero or one time."

Usage example:

var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc'));      // false
console.log(rx.test('309'));      // true
console.log(rx.test('30.9'));     // true
console.log(rx.test('30.85'));    // true
console.log(rx.test('30.8573'));  // false
like image 65
NullUserException Avatar answered Oct 04 '22 10:10

NullUserException