Regex to match from 0.0 to 150.0 (including floating point) - javascript

I have a problem: i should match values from 0.0 to a specific double value (for example, i should match from 0.0 to 150.00 including value as 12, 21.23213, 149.111)
anyone can help me?
i tried everything.
i used this regexp for match by 0.0 to 60.0 but it doesn't work
(^0(\.[0-9]+)?$|^[1-9]{1}(\.[0-9]+)?$|^[1-5]{1}[0-9]{1}(\.[0-9]+)?$|^60$)
with 123 it doesn't work
thank you in advance
Marco

Don't use a regex - use Number, check it's a number with isNaN, then compare values using <= and >=.
e.g.
var your_val = "3.05";
var your_val_num = Number(your_val);
if (!isNaN(your_val_num) && your_val_num >= 0 && your_val_num <= 150) {
// do something
}
N.B. I've changed my answer to use Number rather than parseFloat, per AndyE's comment, and to check for NaN before doing numerical comparisons, per lincolnk's comment.

I agree with the other answers: regex is a poor way to do numeric comparisons.
If you really have to, either:
because a dumb framework you're stuck with only allows regex checks, or
you need extra decimal precision that a JavaScript Number can't provide (as JavaScript has no built-in Decimal type)... this won't be the case for comparing against the whole numbers 0 and 150 though
then:
^0*( // leading zeroes
150(\.0+)?| // either exactly 150
1[0-4]\d(\.\d+)?| // or 100-149.9*
\d{0,2}(\.\d+)? // or 0-99.9*
)$
(newlines/comments added for readability, remove to use.)
This doesn't support E-notation (150=1.5E2) but should otherwise allow what normal JS Number parsing would.

forget regex - just check if(parseFloat(x)=<150 && parseFloat(x)>=0)

Related

Regex allow zero and one decimal point at the beginning or between numbers [duplicate]

I want to modify my existing Regular Expression which accepts decimals from 0 to 99.99
\d{0,2}(\.\d{1,2})?$
i want this to be accept
100
100.0
100.00
and should not accept
100.1
100.02
101
Can anyone help me modify the above RE
I guess it's best to add the test for 100 as a special case using |:
^(\d{0,2}(\.\d{1,2})?|100(\.00?)?)$
Use Floating-Point Comparisons Instead
You already have answers for doing this with a regular expression, but it's usually more efficient to handle this as a floating-point comparison with boundary conditions. For example, using Ruby:
number = 99
number.to_f >= 0 and number.to_f <= 100
=> true
number = 100.01
number.to_f >= 0 and number.to_f <= 100
=> false
In these examples, the variable is cast as a float so that strings and integers are compared properly, and then the float is compared to the boundary conditions of zero and 100. It's quick, easy to write, and (most importantly) easy to read.
Your mileage may vary.
Worked for me from 00.00 to 99.99
/^(?=.*\d)\d{0,2}(?:\.\d{0,2})?$/
100(\.0{1,2})?$|\d{0,2}(\.\d{1,2})?$
(100(\.[0]{1,2})?|[0-9]{1,2}(\.[0-9]{1,2})?)
I think, this will help you "^(100(.0{0,2}?)?$|([1-9]{0,1})([0-9]{1})((.[0-9]{0,2})|(\,[0-9]{0,2}))?)$"
It will match everything between this:
0-100,
0.0 - 100.0,
0.00 - 100.00
and all this with comma.
^(0*(\d{1,2}(\.\d+)?)|\.\d+|100(\.0+$)?)$
This will apply to any values between 0-100 with decimals that are valid for most programming languages
valid: 0, 0.2, .1, 0001.020, 9, 010, 100.0000
invalid: -1, 100.010, 1., ., empty

Match number with no decimal and greater than 10,000

I am not very familiar with regex and am trying to create a regex code in JavaScript to match a string with only
whole numbers
no decimals/dots
and should be greater than 10,000
So far I have it like the ff. I think I am missing something as it still read through decimal numbers and == 10,000. How do I do that?
[1-9](?!\.)\d[0-9]{3,}
https://regex101.com/r/hG2iU7/61
At the risk of not directly answering the question, JavaScript can already parse numbers. Why bother trying to reimplement this? Especially with RegExp?
Why not just parseFloat(theString) or Number(theString) the entire string?
It will fail/return NaN if what you have isn't a number, and you can test for this with isNaN.
If it doesn't fail, you can then test it to ensure that it's an integral value:
const isIntegral = Math.trunc(theNumber) === theNumber;
and is less than 10000
const isLessThan10000 = theNumber < 10000;
This code is going to be much easier to read and maintain than a regular expression.
You may use
^[1-9][0-9]{4,}$
To exclude 10000 add a (?!10000$) lookahead:
^(?!10000$)[1-9][0-9]{4,}$
^^^^^^^^^^
See the regex demo and the regex graph:
Details
^ - start of string
(?!10000$) - a negative lookahead that cancels the match if the whole string is equal to 10000 (i.e. after start of string (^), there is 10000 and then end of string position follows ($))
[1-9] - a digit from 1 to 9
[0-9]{4,} - any four or more digits
$ - end of string.

Regular expression of decimal range 0.025 to 99.999

I know that dozens of similar questions was asked before, but cannot find solution which fits my needs.
I need a regular expression as a pattern for validation purposes, which is a range between 0.025 to 99.999 but should also match integers and any possible decimal forms up to 3 decimals:
1 - matched
1.0 - matched
1.000 - matched
0.025 - matched
0.03 - matched
0.01 - not matched
0.024 - not matched
So far my regex looks like this:
^(?!0*(\.0+)?$)([1-9]?[0-9]\.[0-9]{0,3}|[1-9]?[0-9])?$
It actually matches all between 0.001 and 99.999, because managed how to exclude 0 with decimal forms, but don't know how in the easiest way exclude 0.001 to 0.024.
in javascript you can just convert the string to number and use logic like this
const str = '1.0'
const test = +str;
if(test >= 0.025 && test <= 99.999) {
console.log('valid');
}
IMO this will be simpler and easier to read
EDIT:
as mentioned in comments this will pass for strings like 3e-2 which is valid syntax in javascript to define numbers, so you might have to handle that case based on your use case.
To do this with a regular exression, you need something a bit complex:
^(?:0\.02[5-9]|0\.0[3-9]\d?|0\.[1-9]\d{0,2}|[1-9][0-9]?(?:\.\d{1,3})?)$
Here it is in Regex101
Here is how this works in JS
const regex = /^(?:0\.02[5-9]|0\.0[3-9]\d?|0\.[1-9]\d{0,2}|[1-9][0-9]?(?:\.\d{1,3})?)$/;
const testValues = [ "0", "1", "99.999", "0.025", "0.024", "0.01" ];
testValues.forEach(value => console.log(value, regex.test(value)));
Explanation for the expression: it's a bunch of ORs that cover the value range. Although you can compress it more, I've tried to keep it logical and readable:
0\.02[5-9] - values from 0.025 to 0.029
0\.0[3-9]\d? - values from 0.03 to 0.099. The last digit is optional.
0\.[1-9]\d{0,2} - values from 0.1 to 0.999. The last two digits are optional. The fractional part in each case up to now is mandatory, so 0 is not valid.
[1-9][0-9]?(?:\.\d{1,3}) - values from 1 to 99.999. Again, the decimal point and fractional part are set as optional. If present, you can have 1-3 of them.
the entire regex is wrapped in a non-capturing group and then nested between ^ and $ anchors to make sure that the ENTIRE string matches.
Notable exclusions with this regular expression:
exponential form/scientific notation. For example: 3e1 or 3e-1
numbers that lead with zero. For example: 01, 02.345
numbers that start with a sign. For example: +10
values that start from the decimal part. For example: 0.2, 0.123
values that end in a dot. For example 1., 2.
strings that contain whitespace. For example: " 1" will fail to match. The easiest way to solve this is by ensuring the values are trimmed before being tested.

Need a Reg Expression to find a decimal range

I am currently needing a reg expression which will evaluate a decimal range.
The requirements are as below
1) Can allow only 1 or 2 decimal places after dot or can as well allow whole numbers (e.g) 1234 , 123.4, 1245.78 are valid
2) The range should be within 9999 (e.g) 9999.0 , 9998.99 , 9999.00 - Valid | 9999.01,10000.00 - not Valid
3)Do not require leading or trailing zeros
So far i have tried to achieve till writing this reg expression
/^[0-9]\d{1,4}(\.\d{1,2})?$/.test(value);
... but unable to proceed with setting range till digit 9999 (since 9999.01 also not valid )can you help.
Why don't just apply regular expression to determine is your string a valid digit with dots float, then typecast it to Number and find wether it is bigger than 9999 or not.
Regexp for your needs caould be very complex and take too much CPU from client.
Here's something quick and dirty that should work for you: http://regex101.com/r/vK1jM3
/^(?(?=9999)9999(?:\.0+)?|\d{1,4}(?:\.\d{1,2})?)$/gm
I merely handle the special case of 9999
This works as far as I can see:
^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$
Testing it out:
var monstrosity = /^(9999(?!\.[1-9])(?!\.0[1-9])\.[0-9]{1,2}|9999|(?!9999)[0-9]{1,4}|(?!9999)[0-9]{1,4}\.[0-9]{1,2})$/;
console.log(monstrosity.test("9999.00")); // true
console.log(monstrosity.test("9999.01")); // false
console.log(monstrosity.test("9999")); // true
console.log(monstrosity.test("9998.4")); // true
console.log(monstrosity.test("0")); // true
console.log(monstrosity.test("0.5")); // true
If you add something like this to the codebase, future maintenance programmers will hunt you down with pitchforks. Try to solve the range check without regex, as webbandit suggested.
Why a regexp? Just do
x > 0 && x <= 9999 && (x*100 - Math.floor(x*100) == 0)

JavaScript Number preserve leading 0

I have a problem, I build a very simple javascript search for postal codes.
I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.
value >= splitZips[0] && value <= splitZips[1]
But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.
Any idea how to fix this?
Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.
Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.
Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:
var strPC = "01745",
numPC = +strPC;
alert(numPC === +"01745"); // true
+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.
Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:
/^\d{4,5}$/.test(searchTerm) // returns true or false
Instead a parseInt you could use type casting :)
"0123">"122" // false
+"0123">"122" // true | that means: 123>"122"
Btw, what more you can use a each of bitwise operators :
~~"0123"
"0123"|0
"0123"&"0123"
"0123">>0
"0123"<<0
With the same effect :)

Categories

Resources