FlexMcMurphy
FlexMcMurphy

Reputation: 523

RegEx for a number that must contain a decimal point

I am trying to write a regex to validate a decimal number.

  1. The number MUST contain a decimal point.
  2. There must be one digit [0-9] to the right of the decimal point.
  3. There may be max 5 digits to the left of the decimal point but they cannot start with zero unless a zero on its own.

Allowed:

Not allowed:

This regex validates what comes before the decimal place

^(?:[1-9][0-9]{0,4}|0)$

This regex validates what comes after the decimal place

^[0-9]{1}+$

I just don't know how to combined the two such that the decimal place is mandatory.

How do I solve this problem?

Upvotes: 2

Views: 2352

Answers (3)

felixmosh
felixmosh

Reputation: 35603

That should work

const r = /^(?:[1-9]\d{0,4}|0)\.\d+/

const arr = ['0', '1', '1.2', '1.', '1.123', '0123.1', '123.123', '1234.1', '12345.12345678', '123456.123', '0.12'];

arr.forEach((val) => {
  console.log(val, r.test(val));
})

Upvotes: 0

Emma
Emma

Reputation: 27763

This RegEx might validate your inputs:

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

and you can simply call it using $1.

enter image description here

Upvotes: 0

user557597
user557597

Reputation:

To the best of my knowledge, this works

^(?:[1-9]\d{0,4}|0)\.\d$

Expanded

 ^                             # BOS
 (?:
      [1-9] \d{0,4}                 # 1-5 digits, must not start with 0
   |                              # or,
      0                             # 0
 )
 \. \d                         # decimal point and 1 digit
 $                             # EOS

Upvotes: 4

Related Questions