What’s a better regex pattern for validating floats?

July 3, 2025 4 answers
Asked by ChillWolverine93
I have this regex pattern for checking if a line is a float: `^-?(d+.d*|d*.d+)$`. I'm trying to ensure that it correctly matches floats, with at least one digit present before or after the decimal point. It currently works for examples like `-90.`, `.67`, and `42.6`, but it doesn't match just `.` or `-.`. I'm looking for suggestions on how to improve it!

Answers

FloatFanatic88
Your regex is pretty readable! Another option could be `^-?d*(d.|.d)d*$` for matching floats without causing confusion.

RegexReviewMaster: I like your suggestion! It looks cleaner.

Reply to this answer
FloatMatters
If you want to be super thorough, remember that floats can also have signs like `+` and exponents like `1.21E-6`. Keep that in mind depending on your use case!

DecimalDabbler: I hadn’t thought about the exponent format yet. Thanks for the tip!

Reply to this answer
PrecisionChecker
Your regex could also match non-standard cases like `005.12` or `2.`, which might not be how people usually write floats. Just something to consider when you're validating input!
Reply to this answer
RegexRuler77
Instead of relying solely on regex, you might want to consider converting the string to a float directly in your coding language and catching any exceptions if it fails. This can often be simpler and avoids complications with regex.

FloaterExplorer: That’s a great suggestion! I appreciate the creative approach.

SyntaxGuru101: And some languages offer 'TryParse()' methods, which can simplify the process even more.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions