Skip to content

Instantly share code, notes, and snippets.

@victorfontes
Last active July 24, 2025 00:43
Show Gist options
  • Select an option

  • Save victorfontes/fb7f7d8e62e79319840bc933a11a7cd5 to your computer and use it in GitHub Desktop.

Select an option

Save victorfontes/fb7f7d8e62e79319840bc933a11a7cd5 to your computer and use it in GitHub Desktop.
finance stuff
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
pandas
fastcore
funcy
toolz
boltons
casefy
arrow
python-box
orjson
orjsonl
pydantic
glom
jsonpath-ng
import re
from decimal import Decimal
def parse_percent(pct_str: str) -> float:
"""
Parses a percentage string into a float value.
Handles formats like "14,90%", "200 %", and "50%", supporting both "." and "," as decimal separators.
Converts the percentage to a decimal (e.g., 14,90% becomes 0.149).
"""
if isinstance(pct_str, (float, Decimal)):
pct_str = str(pct_str)
cleaned_string = pct_str.replace(" ", "").replace("%", "")
# Replace comma with a dot for decimal conversion if a comma exists
if "," in cleaned_string and "." not in cleaned_string:
cleaned_string = cleaned_string.replace(",", ".")
# If both exist, assume comma is the decimal separator and remove dots as thousand separators
elif "," in cleaned_string and "." in cleaned_string:
cleaned_string = cleaned_string.replace(".", "").replace(",", ".")
try:
return float(cleaned_string) / 100
except ValueError:
raise ValueError(f"Could not parse '{pct_str}' as a percentage."))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment