JavaScript regular expression for decimal numbers

999 views Asked by At

I'm looking for a regular expression in JavaScript that tests whether a string is a number with one or two digits before the decimal point and optionally a maximum of five digits after decimal point.

Examples of correct values:

  • 12.345
  • 12.12
  • 1.3
  • 1.12345
  • 12

What would be the correct regex for this?

2

There are 2 answers

0
John Slegers On

Regex

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

Demo

var regexp = /^\d{1,2}(\.\d{1,5})?$/;

console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'100.5' returns " + regexp.test('100.5'));
console.log("'82.744' returns " + regexp.test('82.744'));
console.log("'13.' returns " + regexp.test('13.'));
console.log("'.744' returns " + regexp.test('.744'));
console.log("'.74400' returns " + regexp.test('.74400'));
console.log("'5.74400' returns " + regexp.test('5.74400'));


Explanation

  1. / / : the beginning and end of the expression
  2. ^ : whatever follows should be at the beginning of the string you're testing
  3. \d{1,2} : there should be one or two digits here
  4. ( )? : this part is optional
  5. \. : here goes a dot
  6. \d{1,5} : there should be between one and five digits here
  7. $ : whatever precedes this should be at the end of the string you're testing

Tip

You can use regexr.com or regex101.com for testing regular expressions directly in the browser!

6
Mustofa Rizwan On

you can try that:

^\d{1,2}(\.\d{1,5})?$

Explanation:

  1. ^ start of a string
  2. \d{1,2} 1 to 2 digit number
  3. ( opening capture group
  4. \. dot
  5. \d{1,5} number 1 to 5 digit
  6. ) closing capture group
  7. ? makes the entire capture group optional

$ end of string

Demo

const regex = /^\d{1,2}(\.\d{1,5})?$/gm;
const str = `12.121`;

console.log(regex.test(`12.121`));
console.log(regex.test(`1`));
console.log(regex.test(`1.1`));
console.log(regex.test(`12.123`));
console.log(regex.test(`1.123`));
console.log(regex.test(`1.1234567`));