Skip to content Skip to sidebar Skip to footer

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 hel

Solution 1:

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
}

Solution 2:

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 zeroes150(\.0+)?|             // either exactly 1501[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.

Solution 3:

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

Post a Comment for "Regex To Match From 0.0 To 150.0 (including Floating Point)"