Created
April 17, 2025 09:59
-
-
Save mrtnzlml/95bece19d08bcdfd317e45be8b90cf82 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parse_float_or_none(s): | |
""" | |
Attempts to convert a string to a float, handling various decimal and thousands separators. | |
Recognizes comma (','), dot ('.'), and space (' ') as potential separators. | |
Interprets: | |
- "1 234,56" as 1234.56 | |
- "1.234,56" as 1234.56 | |
- "1,234.56" as 1234.56 | |
- "1234,56" as 1234.56 | |
Args: | |
s (str): The input string representing a number. | |
Returns: | |
float or None: The converted float, or None if conversion fails. | |
""" | |
try: | |
s = s.strip().replace(' ', '') | |
if ',' in s and '.' in s: | |
if s.rfind(',') > s.rfind('.'): | |
s = s.replace('.', '').replace(',', '.') | |
else: | |
s = s.replace(',', '') | |
elif ',' in s: | |
s = s.replace(',', '.') | |
return float(s) | |
except ValueError: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment