What's a better regex for validating floats?

July 3, 2025 5 answers
Asked by CuriousCoder42
I'm working on a regex to check if a given string is a float and I want it to handle both cases where there are digits before and/or after the decimal point, while ensuring there's at least one digit. The regex I'm currently using is `^-?(d+.d*|d*.d+)$`. This matches inputs like `-90.`, `.67`, and `42.6`, but it fails for `.` and `-.`. Any suggestions for improvement?

Answers

DetailDude
Your regex might match values like `005.12`, which is technically okay, but not how many people write floats. You should also consider the case of `2.`, which is uncommon and could signal a formatting error.
Reply to this answer
FloatMaster3000
Another version of your regex could be: `^-?(d+?.d*|.d+)$`. This ensures there's at least one digit on either side of the decimal, which should help filter out invalid strings like `-` or `.`!
Reply to this answer
PatternGuru22
Your regex isnโ€™t bad! Just remember that there are many ways to define floats in regex, and it's all about what you need to match. A different approach might be using `^-?d*(d.|.d)d*$`, which could work better for your goals.

HelpfulHan: Thanks! I agree that I find mine more readable too.

Reply to this answer
FloatFanatic
Donโ€™t forget that a float can also begin with a `+` or have an exponent. For example: `+1.21E-6`. And also keep in mind that most languages will consider `10` a valid float even though thereโ€™s no decimal point.

InquisitiveUser: Hmm, I'm not sure if I need to account for exponents. I'm practicing with a project where Iโ€™m intentionally separating floats and ints.

Reply to this answer
RegexNinja99
Have you considered that, depending on the programming language, it might be easier to just try converting the string to a float? You could catch exceptions if the conversion fails, which might simplify things for you!

ThoughtfulTabby: I love out-of-the-box thinking!

CodeAnalyzer88: Some languages offer a method like TryParse(), which could avoid exceptions. It returns a simple Boolean flag to indicate whether the conversion succeeded, which might suit your needs better!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions