What’s a Better Regex for Validating Floats?

0
8
Asked By CuriousCat42 On

I'm trying to improve my regex for checking if a string is a float. Currently, I have `^-?(d+.d*|d*.d+)$`. This works for numbers like `-90.`, `.67`, and `42.6`, but it doesn't recognize single dots `.` or negative single dots `-.` as valid. I'm looking for a way to ensure that there are digits both before and/or after the decimal point while preventing those invalid cases.

7 Answers

Answered By FloatExpert85 On

Keep in mind that a float can also start with a + and may have an exponent, e.g., `+1.21E-6`. Also, just to note, `10` is a valid float too, even without a decimal point.

CuriousCat42 -

Good point! I hadn't considered the exponent format since I'm separating floats from integers for this project.

Answered By SimpleScriptor On

Yours is quite readable, but you could also try something like `^-?d*(d.|.d)d*$` for clarity. That keeps the same checks but may look nicer!

CuriousCat42 -

Thanks for the tip! I agree that readability is key!

Answered By CodeSeeker On

Another way to refine it is with `^-?(d+?.d*|.d+)$`, while still making sure there's at least one digit around the decimal. This won’t allow `-` or `.` since neither has digits.

Answered By AnalyticalCoder On

Your regex matches inputs like `005.12`, which are valid but not how people typically write floats. It also accepts `2.`, which seems off since that’s not common.

Answered By RegexWhiz On

Your regex isn't bad! Just remember that regex can vary, and there are multiple ways to define what a float is. It might be worth exploring those alternatives.

FloatGuru -

True! Your regex doesn’t match numbers like 1.3e3 or 1.3e-3, which could be important.

Answered By RegexRanger99 On

You might consider using string-to-float conversion instead; just try converting and catch exceptions for invalid cases. It can be simpler depending on the language you're using!

OptimisticCoder1 -

That's some great out-of-the-box thinking!

DevHelpMaster -

Some languages have methods like TryParse() which could help here. It checks if conversion works and returns a flag without throwing an exception. So if you need to clean your data for another system, ensure you know what formats are accepted there!

Answered By AnonymousUser On

[deleted]

CommentNoted -

Your regex fails to match the first example of valid inputs.

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.