SO is already filled with quite a number of questions regarding to Python's locale settings for formatting a number with corresponding thousands and decimal separators, the best of which I believe is found here.
However, I have been trying to build upon this solution by extending its functionality to percentages as well, to no avail:
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
def pbr(number, isfloat=True):
if isfloat:
return locale.format_string('%.2f', number, grouping=True)
else:
return locale.format_string('%.2%', number, grouping=True) # Not working
Obviously '%.2%'
is not a valid formatter, but I don't know what should be done so that
In [1]: pbr(81.23421039401, isfloat=False)
Out[1]: '8.123,42%'
Also, is this implementation of the locale solution (including the format_string
function syntax which seems to be some leftover of the Python 2 era) still optimal, considering Python 3.8?
Looking at the Python documentation and Python reference for string formatting, it seems that you are trying to use the %
operator from the "new formatting style" in the "old formatting style", where it meant something else. This explains why your method fails.
One way to achieve what you want with the locale is to do the multiplication and add the %
sign yourself:
import locale
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
def pbr(number, isfloat=True):
if isfloat:
return locale.format_string('%.2f', number, grouping=True)
else:
return locale.format_string('%.2f%%', number*100, grouping=True)
I cannot say whether this is still optimal in Python 3.8, I feel there should be a way to simply use string.format with the new style but I haven't yet found the way to make it use the locale.