One option is to use locale.format
(up to Python 3.6), or locale.format_string
(from Python 3.7 as in this version locale.format
became deprecated):
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')
print(locale.format_string('%.2f', 10.00)) # 10,00
First I use setlocale
to indicate that I want to use the locale pt_BR
(Brazilian Portuguese), where the decimal separator is the comma. Then, just indicate the format %.2f
, that says to format the number with two decimal places.
The interesting thing about this module is that it allows a greater control over formatting, which I think is more appropriate than staying replace
. For example, you can also indicate whether or not you will have the thousands separator, if the value is greater than 1000:
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')
# sem separador de milhares
print(locale.format_string('%.2f', 12345.00)) # 12345,00
# com separador de milhares
print(locale.format_string('%.2f', 12345.00, True)) # 12.345,00
Besides being able to format as a monetary value (I don’t know if that was the intention):
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')
# sem separador de milhares
print(locale.currency(12345.00)) # R$ 12345,00
# com separador de milhares
print(locale.currency(12345.00, grouping=True)) # R$ 12.345,00
The detail is that this module uses C libraries to get the format referring to the locale, according to the documentation:
The locale
module is implemented on top of the _locale
module, which in turn uses an ANSI C locale implementation if available.
Then the locale pt_BR
must be installed/configured on the operating system for it to work. Otherwise, the alternative is to use replace
even, as suggested in another answer.
I think it might help: How to limit decimal numbers in Python?.
– Gustavo Sampaio