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
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
Share Improve this question edited Sep 8, 2010 at 13:00 Colin Hebert 93.2k15 gold badges162 silver badges153 bronze badges asked Sep 8, 2010 at 12:58 marcomarco 111 bronze badge 2- 10 Why not just turn it into a float and check its numeric value? – BoltClock Commented Sep 8, 2010 at 13:01
- 6 PLEASE, FOR THE LOVE OF GOD, DO NOT USE A REGEX! AAAAAAGH! – John Gietzen Commented Sep 8, 2010 at 13:03
3 Answers
Reset to default 14Don't use a regex - use Number
, check it's a number with isNaN
, then pare 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 ment, and to check for NaN
before doing numerical parisons, per lincolnk's ment.
I agree with the other answers: regex is a poor way to do numeric parisons.
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 paring 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/ments 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)