Neil Neil - 28 days ago 9
jQuery Question

javascript regex: if string contains decimal, only allow two digits after the decimal

Ultimately I want to write a regex that allows an integer number, or a decimal number with 0 - 2 decimal digits.

Valid Input

1
1.
1.1
1.11
111111111
111111111.
111111111.1
111111111.11


Invalid Input

a
a.
1.a
1.111
1.1111



  • string allows any number of digit characters, but only allows 1 decimal/period


    • if a period/decimal exists: only allow 2 digit characters after the decimal




Here is the regex I came up with

\d*\.?([\d]){0,2}


I am having trouble testing it to ensure it works. I found a couple ways of testing it. Using the
test
method which I just used w3schools setup here. The other way was with some javascript regular expression tester like regexr and regex101. For all of these: it appears that either my regular expression is returning false positives, or my regular expression does not work as intended.

Question: What regex would do what I want it to do?

Answer
  1. You need to make sure that you check the complete string (from the first char to the last char) using ^...$
  2. The first digit should appear at least 1 time (so you want to use + and not *).

Check this example:

r = /^\d+\.?\d{0,2}$/
tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
  console.log(val, val.match(r) ? ': valid' : ': invalid');
});

update

Following the comments - if you need a solution for "integer number, or a decimal number with 0 - 2 decimal digits" (like you said in the question, but not like the valid input section), you can use this:

r = /^\d+(\.\d\d{0,1})?$/
console.log('1.'.match(r))

tests = ['1', '1.', '1.1', '1.11', '111111111', '111111111.', '111111111.1', '111111111.11', 'a', 'a.', '1.a', '1.111', '1.1111']
tests.forEach(function(val) {
  console.log(val, val.match(r) ? ': valid' : ': invalid');
});

Comments