use the `locale.currency` library function
- 1 minutes read - 133 wordsI had stupidly written a pair of functions like this:
def comma_sep(amount):
thousands = int(amount/1000)
remainder = int(amount%1000)
if thousands > 0:
return comma_sep(thousands)+","+"%.3d"%(remainder)
else:
return str(remainder)
def friendly_from_cents(total_cents):
pos = total_cents >= 0
total_cents = abs(total_cents)
cents = int(total_cents%100)
dollars = int(total_cents/100)
friendly = "$"+comma_sep(dollars)+"."+str(cents)
if pos:
return friendly
else:
return "-" + friendly
This is stupid, because python has builtin support to localize currency:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.currency(-1800, grouping=True)
I think it’s tempting to fall into these traps, because it always starts simpler:
I had some total_cents
variable and just wanted to display quick and dirty.
The complexity built up gradually, until I had something pretty complicated.
Oops.
More generally, I violated the “Use the batteries” idiom of Python – which is something I actually try to do. Kinda embarrassing.