user1458019
user1458019

Reputation: 41

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.

Upvotes: 1

Views: 234

Answers (4)

user663031
user663031

Reputation:

Why a regexp? Just do

x > 0 && x <= 9999 && (x*100 - Math.floor(x*100) == 0)

Upvotes: 0

Deestan
Deestan

Reputation: 17136

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.

Upvotes: 0

s.webbandit
s.webbandit

Reputation: 17000

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.

Upvotes: 2

Firas Dib
Firas Dib

Reputation: 2621

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

Upvotes: 0

Related Questions