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?