简体   繁体   English

验证一系列浮点数

[英]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.我希望它验证数字是否在 0 和 1 之间以及小数点后的数字。

The problem with the regex at the top is that it also accepts the numbers 1.11, 1.21.顶部的正则表达式的问题是它也接受数字 1.11、1.21。 1.3 etc. 1.3 等

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, eg 0-2.99, 3-13.21, and so on.这个正则表达式也必须是通用的,因为我将用一个变量替换 0 到 1 之间的数字,并且那里可能有不同的值,例如 0-2.99、3-13.21 等等。

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:如果您要比较 3 个数字变量,那么您可以使用这个简单的函数:

 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM