Regex to match from 0.0 to 150.0 (including floating point)
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}(\.开发者_JS百科[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)
精彩评论