What’s a better regex for validating floating-point numbers?

0
8
Asked By CuriousCoder99 On

I'm currently using the regex `^-?(d+.d*|d*.d+)$` to check if a string is a valid float. It works for inputs like `-90.`, `.67`, and `42.6`, but it fails for just `.` or `-.`. I'm looking for ways to improve this regex so it can handle digits before and after the decimal point while ensuring at least one digit is present. Any suggestions?

6 Answers

Answered By PrettyFloat99 On

Just a heads up—your regex will match numbers like `005.12`, which is technically valid but not typically how floats are represented. Also, `2.` might show up in your matches, which could indicate an input error.

Answered By RegexEnthusiast27 On

You might consider just trying to convert the string to a float, depending on the programming language you're using. If the conversion fails, then you can catch the exception. It's a straightforward way to handle it without overcomplicating your regex.

FloatFinder42 -

That's a clever approach! It really simplifies things.

LanguageLover88 -

Some languages even have a `TryParse()` method that checks validity without the overhead of exceptions, returning a success flag and the result.

Answered By RegexRanger14 On

If you're looking for readability, you might try something like `^-?d*(d.|.d)d*$`. It keeps it simple and clear.

CuriousCoder99 -

Thanks! I appreciate the suggestion; readability is important to me.

Answered By FloatGuru73 On

A more precise regex based on your needs could be `^-?(d+?.d*|.d+)$`. This ensures at least one digit on either side of the decimal, and it won't match just `-` or `.` since those don't contain digits.

Answered By RegexNinja05 On

Your current regex isn't bad! However, remember that regex can vary by language, and there are many formats for defining floats.

MathMaven21 -

True! For example, your regex might not account for scientific notation like `1.3e3` or `1.3e-3`.

Answered By FloatJunkie08 On

Also, keep in mind that valid floats can start with a `+` sign or include an exponent, like `+1.21E-6`. And in many languages, `10` would also be considered a float even without a decimal point.

CuriousCoder99 -

That's a good point! I'm focusing on separating floats and ints, so I'm not considering exponents right now.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.