Created
March 25, 2025 13:57
-
-
Save Lenochxd/154af86f1704e6525de3b94cde4d95b8 to your computer and use it in GitHub Desktop.
Convert a price string into a float, handling different formatting styles.
This file contains 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
import re | |
def parse_price(price: str) -> float: | |
""" | |
Convert a price string into a float, handling different formatting styles. | |
- Supports "1,123.23" (English format) -> 1123.23 | |
- Supports "1123,23" (European format) -> 1123.23 | |
- Supports "1.123,23" (European thousand separator) -> 1123.23 | |
- Supports "1,123" (English thousand separator) -> 1123.0 | |
- Supports "1123" (plain number) -> 1123.0 | |
- Rejects ambiguous formats | |
Raises: | |
ValueError: If the format is ambiguous or invalid. | |
""" | |
price = price.strip() | |
# Check if both '.' and ',' are present | |
if '.' in price and ',' in price: | |
if price.rfind('.') > price.rfind(','): | |
# English format: "1,123.23" | |
price = price.replace(',', '') | |
else: | |
# European format: "1.123,23" | |
price = price.replace('.', '').replace(',', '.') | |
# If only ',' is present, determine if it's a decimal or thousand separator | |
elif ',' in price: | |
if price.count(',') == 1 and len(price.split(',')[-1]) == 2: | |
# Likely a decimal separator (European style) | |
price = price.replace(',', '.') | |
else: | |
# Likely a thousand separator (English style) | |
price = price.replace(',', '') | |
# If only '.' is present, assume it's a decimal separator | |
# Ensure the result is a valid number | |
if not re.fullmatch(r'\d+(\.\d+)?', price): | |
raise ValueError(f"Invalid price format: {price}") | |
return float(price) | |
if __name__ == "__main__": | |
# Example usage: | |
prices = ["1,123.23", "1123,23", "1.123,23", "1,123", "1123"] | |
for p in prices: | |
try: | |
print(f"{p} -> {parse_price(p)}") | |
except ValueError as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment