Fresh code
Fresh code

Reputation: 13

Validation of a range of floating point numbers

I have been looking for a long time and trying to write a regex, but not successfully.

Currently I have such a regex

/^([0-1](\.\d+)?)$/

and I would like it to validate if the number is between 0 and 1 along with the numbers after the decimal point.

The problem with the regex at the top is that it also accepts the numbers 1.11, 1.21. 1.3 etc.

I tried to do something like this but it doesn't work

/^([0(\.\d+)-1]?)$/

This regex also has to be universal because I will substitute a variable for the number between 0 and 1, and there may be different values there, e.g. 0-2.99, 3-13.21, and so on.

Upvotes: 0

Views: 230

Answers (1)

zer00ne
zer00ne

Reputation: 43910

Using Regex to find a given number within the range of two numbers is like using a fork to scoop up water. Regex is used to find patterns within strings. You are using real numbers not strings. If you are comparing 3 variables that are numbers then you can use this simple function:

const range = (num, min, max) => min <= num && num <= max;

console.log(range(1.11, 0, 1));
console.log(range(2.991, 0, 2.99)); 
console.log(range(13.0000001, 3, 13.21));
console.log(range(5.69, 0, 6));

Upvotes: 1

Related Questions