Skip to content

Instantly share code, notes, and snippets.

@mrtnzlml
Created April 17, 2025 09:59
Show Gist options
  • Save mrtnzlml/95bece19d08bcdfd317e45be8b90cf82 to your computer and use it in GitHub Desktop.
Save mrtnzlml/95bece19d08bcdfd317e45be8b90cf82 to your computer and use it in GitHub Desktop.
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