Answers
Favour George 2018-05-13T20:00:18
If you want your code to pick a specific range of digits, be sure to use the && operator instead of the ||. \n\n\r\n\r\nif (x >= 4 && x <= 9) {\r\n // do something\r\n} else {\r\n // do something else\r\n}\r\n\r\n// be sure not to do this\r\n\r\nif (x >= 4 || x <= 9) {\r\n // do something\r\n} else {\r\n // do something else\r\n}",
De Bonheur 2019-09-25T13:58:39
You must want to determine the lower and upper bound before writing the condition\n\nfunction between(value,first,last) {\n\n let lower = Math.min(first,last) , upper = Math.max(first,last);\n return value >= lower && value <= upper ;\n\n}\n",
Pointy 2011-06-23T12:47:28
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need \"multiple if\" statements to do it, either:\n\nif (x >= 0.001 && x <= 0.009) {\n // something\n}\n\n\nYou could write yourself a \"between()\" function:\n\nfunction between(x, min, max) {\n return x >= min && x <= max;\n}\n// ...\nif (between(x, 0.001, 0.009)) {\n // something\n}\n",
Alexander 2018-04-09T02:51:49
Here is an option with only a single comparison.\n\n// return true if in range, otherwise false\nfunction inRange(x, min, max) {\n return ((x-min)*(x-max) <= 0);\n}\n\nconsole.log(inRange(5, 1, 10)); // true\nconsole.log(inRange(-5, 1, 10)); // false\nconsole.log(inRange(20, 1, 10)); // false\n",
Alnitak 2011-06-23T12:55:28
If you must use a regexp (and really, you shouldn't!) this will work:\n\n/^0\\.00([1-8]\\d*|90*)$/\n\n\nshould work, i.e.\n\n\n^ nothing before,\nfollowed by 0.00 (nb: backslash escape for the . character)\nfollowed by 1 through 8, and any number of additional digits\nor 9, followed by any number of zeroes\n$: followed by nothing else\n",
Haroldo_OK 2020-02-17T19:44:36
If you're already using lodash, you could use the inRange() function:\nhttps://lodash.com/docs/4.17.15#inRange\n\n_.inRange(3, 2, 4);\n// => true\n\n_.inRange(4, 8);\n// => true\n\n_.inRange(4, 2);\n// => false\n\n_.inRange(2, 2);\n// => false\n\n_.inRange(1.2, 2);\n// => true\n\n_.inRange(5.2, 4);\n// => false\n\n_.inRange(-3, -2, -6);\n// => true\n",
user736893 2017-06-07T15:14:42
I like Pointy's between function so I wrote a similar one that worked well for my scenario.\n\n/**\n * Checks if an integer is within ±x another integer.\n * @param {int} op - The integer in question\n * @param {int} target - The integer to compare to\n * @param {int} range - the range ±\n */\nfunction nearInt(op, target, range) {\n return op < target + range && op > target - range;\n}\n\n\nso if you wanted to see if x was within ±10 of y:\n\nvar x = 100;\nvar y = 115;\nnearInt(x,y,10) = false\n\n\nI'm using it for detecting a long-press on mobile:\n\n//make sure they haven't moved too much during long press.\nif (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);\n",