简体   繁体   中英

Regex to allow decimal numbers greater than 0 and less than 100

I am trying to enter value greater than 0 and less than 100 and i am using the following regex:

/^(0+)?(99(\.99?)?|(\.99?)?|\.[0-9]+|0?[0-9](\.[0-9]{0,2})?|(0+)?[0-9][0-9](\.[0-9][0-9]?)?)$/

this regex does not complain about zero but 0.01 is a valid value.

Basically, I am trying to get the value in a 00.00 format and it is also acceptable to have values like 0.01, 00.01, ... 99.99 but strictly numbers and dot only.

I am using and

^(?!0?0\.00$)\d{1,2}\.\d{2}$

You can simply use this.See demo.

https://regex101.com/r/qB0jV1/10

So why do you have to beat your self up with a complex regex. Why not a number comparison?

function validNum (num) {
   num = parserFloat(num);

   return num > 0 && num < 100;
}

Want only two decimal places ?

function validNum (num) {
   num = parseFloat((num + "").replace(/^(.*\.\d\d)\d*$/, '$1'));

   return num > 0 && num < 100;
}

Test Here

.5:      true
..5    : false
.005   : false
0.05   : true
99.99  : true
00.01  : true
00.00  : false
0.00   : false
00.0   : false
100.00 : false

I think you don't want to allow 0.00 or 00.00

^(?!00?\.00$)\d{1,2}(?:\.\d{2})?$

OR

^(?!00?\.00$)\d{1,2}(?:\.\d{1,2})?$

DEMO

Negative lookahead at the start (?!00?\\.00$) asserts that the number going to match wouldn't be 00.00 or 0.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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