Skip to content

Instantly share code, notes, and snippets.

@satya10x
Created May 22, 2014 18:33
Show Gist options
  • Save satya10x/0d53c850baf7e255079d to your computer and use it in GitHub Desktop.
Save satya10x/0d53c850baf7e255079d to your computer and use it in GitHub Desktop.
Python currency formatting.
def format_currency(value, currency, add_symbol=False):
# Check if value exists
if value:
# stores the negative symbol
symbol = ""
formatted_currency = ""
dec = ""
value = str(value)
# remove minus sign
if "-" in value:
value = value.split("-")
symbol = "-"
#check if decimal and split
if "." in value:
value, dec = value.split(".")
dec = "." + dec
# recursive splitting of currency
if len(value) > 3:
def rec_split(value, formatted_currency):
if len(value) == 3:
return formatted_currency + value
elif len(value)%2 == 1:
formatted_currency = formatted_currency + value[0:2] + ","
return rec_split(value[2:len(value)], formatted_currency)
elif len(value) %2 == 0:
formatted_currency = formatted_currency + value[0:1] + ","
return rec_split(value[1:len(value)], formatted_currency)
return symbol + rec_split(value, formatted_currency) + dec
else:
return symbol + value + dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment