Home > Enterprise >  Regex decimal greater than 0 less than 1 with at most 3 decimal places
Regex decimal greater than 0 less than 1 with at most 3 decimal places

Time:01-10

I want to make a decimal number that is greater than 0 and less than 1, with at most 3 decimal places. So 0, 0.0004, 0.00, 00.004, are NOT valid. But 0.004 is valid.

I thought this shall be simple but couldn't get it working. This is what I came up with: /^0(?:\.)([1-9]{1,3}?$)/g which makes 0.004 invalid but 0.004 is valid.

CodePudding user response:

You may use this regex with a negative lookahead assertion to disallow all zeroes after dot:

^0\.(?!0 $)\d{1,3}$

RegEx Demo

RegEx Details:

  • ^: Start
  • 0\.: Match 0.
  • (?!0 $): Make sure we don't have all zeroes ahead
  • \d{1,3}: Match 1 to 3 digits
  • $: End

Above regex uses anchors assuming only one such number per line. If there are multiple decimal numbers per line then use word boundary instead of anchors:

\b0\.(?!0 $)\d{1,3}\b

If trailing 0 is not be allowed after dot then use:

^0\.\d{0,2}[1-9]$
\b0\.\d{0,2}[1-9]\b

RegEx Demo 2

CodePudding user response:

While regex tend to be short, they're also cryptic. If you're open to alternatives:

const validate = n => {
  n = Number.parseFloat(n) * 1000;
  return Number.isInteger(n) && n > 0 && n < 1000;
};

CodePudding user response:

This regular expression should do the trick

^0\.\d{1,3}$

You can test it here

https://regex101.com/r/IwQsaD/1

  •  Tags:  
  • Related