Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python number formatting

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

like image 591
Bostjan Avatar asked Jul 21 '26 03:07

Bostjan


1 Answers

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
like image 64
abdullahselek Avatar answered Jul 23 '26 15:07

abdullahselek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!