What’s a better regex pattern for validating floats?

0
6
Asked By ChillWolverine93 On

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!

4 Answers

Answered By RegexRuler77 On

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.

SyntaxGuru101 -

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

FloaterExplorer -

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

Answered By PrecisionChecker On

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!

Answered By FloatMatters On

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!

Answered By FloatFanatic88 On

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.

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.