What's the best regex for validating floats?

July 5, 2025 6 answers
Asked by +clarify the premise
I'm trying to create a regex pattern that can effectively identify float numbers. My current regex is `^-?(d+.d*|d*.d+)$`, which works well for cases like `-90.`, `.67`, and `42.6`, but it fails for just `.` or `-.`. Is there a more efficient way to cover different float formats, ensuring at least one digit is present before or after the decimal point?

Answers

3jaw_chuck
Just a heads up, your regex will still match values like `005.12`, which although valid, might not be how most people write floats. Plus, it accepts `2.` which could indicate a user input mistake.
Reply to this answer
planter_71
Your regex isn't bad! Just remember, regex can vary between languages and there are numerous ways to define a float. So there might be simpler options out there.

loose leaf binder: Exactly! For instance, it won't match scientific notation like `1.3e3` or `1.3e-3`.

Reply to this answer
_quiet.recess
Yours is pretty readable! You could also consider a pattern like `^-?d*(d.|.d)d*$` which covers floats well.

RoughlySpeaking: Thanks! I really do find mine more straightforward.

Reply to this answer
delta.wave.study
Instead of relying on regex, depending on the programming language you're using, you could just try converting the string to a float directly. If it fails, catch the exception. It's often simpler than writing complex patterns!

PHASE.shift: That's a solid point! It's a creative way to handle it.

horizon-level: Some languages have a method like TryParse() that avoids exceptions, giving you a success flag instead. But if you're sanitizing input for another system, you'll want to match what they accept.

Reply to this answer
3beat.rest
Don't forget that floats can start with a `+` and may include exponents, like `+1.21E-6`. Also, many languages view `10` as a valid float without requiring a decimal point.

+clarify the premise: Good point! I didn't plan to include exponent formats for now since I'm separating floats and ints in my project.

Reply to this answer
pH5.8_field
If you're looking to match exactly one digit on either side of the decimal, you might want to use: `^-?(d+?.d*|.d+)$`. This won't allow for just `-` or `.` since those have no digits.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions