Sometimes, we want to do currency formatting in Python.
In this article, we’ll look at how to do currency formatting in Python.
How to do currency formatting in Python?
To do currency formatting in Python, we can use the locale.setlocale
method.
For instance, we write:
import locale
locale.setlocale(locale.LC_ALL, '')
c = locale.currency(188518982.18, grouping=True)
print(c)
We call locale.setlocale
to set the locale of the script by getting the locale settings from the operating system by setting it to locale.LC_ALL
.
Then we call locale.currency
with the float to format into a currency string.
And we set grouping
to True
to group the digits with the digits separator according to the locale.
Therefore, c
is $188,518,982.18
given that the OS’ locale is 'English_United States.1252'
.
Conclusion
To do currency formatting in Python, we can use the locale.setlocale
method.