What’s a better regex for detecting floats?

0
0
Asked By CuriousCat123 On

I'm trying to improve my regex for identifying float numbers. The current regex I have is `^-?(d+.d*|d*.d+)$`, which works for cases like `-90.`, `.67`, and `42.6`. However, it doesn't accept inputs like `.` or `-.`, and I'm wondering if there's a better way to handle digits before and after the decimal point while ensuring at least one digit is present. Any suggestions?

4 Answers

Answered By RegexFanatic On

Your regex is decent. Just remember, there are multiple ways to define floats in regex. You might need to consider options for scientific notation, like `1.3e3`, too. Also, keep in mind cases where a float can be presented without a decimal, like `10` which is still a valid float.

PrecisionSeeker -

For sure! It's good to think about variations and not just stick to one style.

Answered By ExtensiveRegex On

Here's another version that matches a valid float while ensuring there's at least one digit on either side of the decimal: `^-?(d+?.d*|.d+)$`. This will prevent false positives like `-` or `.` as valid floats.

Answered By FloatCritic On

Your regex would match things like `005.12`, which isn’t typically how floats are expressed. It also allows for odd formats like `2.`, which might indicate input errors. Consider refining your criteria for what constitutes a valid float.

Answered By FloatFinder On

If you're looking for readability, try something like `^-?d*(d.|.d)d*$`. It’s simpler and covers the need for at least one number on either side of the decimal.

RegexEnthusiast -

Thanks for the suggestion! I definitely lean towards the more readable approach.

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.