3

I have an issue with formatting number output in Python. I found quite some examples how to do it with .format(), but I can not figure it out how to set it up to my desired output.

I would like to have "." as thousand separator and "," as decimal (e.g. 7.654,32). If I want to do it vice-versa, I would use e.g. print("{0:,.2f}".format(7654.321)), but I can not find the opposite. If nothing else, I could use replace(), but would prefer an elegant solution, as I would use that further with Jinja2 in my html template.

Thank you and best regards,

Bostjan

Bostjan
  • 1,455
  • 3
  • 14
  • 22
  • Have you tried setting the `locale` as used here: https://stackoverflow.com/a/5513747/4636715 – vahdet Apr 04 '18 at 08:19
  • Hello vahdet. Thanks for your answer. I have been playing with locale as well, but I would prefer to code it in a single line, as I am using this in html code with Jinja2 - e.g.{{ "{0:,}".format(type.1) }} – Bostjan Apr 04 '18 at 08:43

2 Answers2

0

You can use Babel for many types of utilities. For your case I think format_number and format_decimal is ideal. First you can install Babel with pip install Babel. And formatting your number you can use de_DE as locale.

from babel.numbers import format_number

formatted_number = format_number(7654.321, locale='de_DE')
print(formatted_number)
>>> 7.654,321
abdullahselek
  • 7,893
  • 3
  • 50
  • 40
  • Hello Abdull, thank you for answer. This indeed works on single number. I run into issue than that I am using pandas df to populate html template via Jinja2 (using df.as_matrix()). I wonder if there is any simple solution, where you specify format of output e.g. "{:,.2f}".format()? – Bostjan Apr 04 '18 at 11:31
  • 1
    The other simple solution might be replacing. Single line and simple without any dependency `formatted_number = "{:,.2f}".format(7654.321).replace(",", "X").replace(".", ",").replace("X", ".")`. – abdullahselek Apr 04 '18 at 11:51
  • Perfect, this is what I was looking for, thank you very much for this :) – Bostjan Apr 04 '18 at 13:18
0

If you don't want to use any other packages and still one-liner

num = 7654.321
format(int(num), ",d").replace(",",".") + "," + "{0:,.2f}".format(num-int(num))[2:]
Rao Sahab
  • 1,161
  • 1
  • 10
  • 12
  • Hello, thanks for feedback. This (along with Abdull's response) work as well, thank you for that. – Bostjan Apr 09 '18 at 09:15