Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created March 8, 2020 16:10
Show Gist options
  • Save luizomf/b392159da86a48b99bfd73dd641d7733 to your computer and use it in GitHub Desktop.
Save luizomf/b392159da86a48b99bfd73dd641d7733 to your computer and use it in GitHub Desktop.
import locale
from typing import Union
lc_ctype = 'pt_BR.utf-8'
locale.setlocale(locale.LC_ALL, lc_ctype)
def number_format(val: Union[str, int, float]) -> str:
""" Number format -> N,NN """
try:
number = float(val)
return locale.format_string('%.2f', number)
except ValueError:
return str(val)
def price_format(val: Union[str, int, float]) -> str:
""" Currency format -> Symbol + N.NNN,NN """
try:
price = float(val)
return locale.currency(price, grouping=True, symbol=True)
except ValueError:
return str(val)
if __name__ == "__main__":
print(number_format('55')) # 55,00
print(price_format('5555')) # R$ 5.555,00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment