[ACCEPTED]-How do I change my float into a two decimal number with a comma as a decimal point separator in python?-decimal
Accepted answer
To get two decimals, use
'%.2f' % 1.2333333
To get a comma, use 2 replace()
:
('%.2f' % 1.2333333).replace('.', ',')
A second option would be to change the locale to some place 1 which uses a comma and then use locale.format()
:
locale.setlocale(locale.LC_ALL, 'FR')
locale.format('%.2f', 1.2333333)
The locale module can help you with reading and writing 1 numbers in the locale's format.
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'sv_SE.UTF-8'
>>> locale.format("%f", 2.2)
'2,200000'
>>> locale.format("%g", 2.2)
'2,2'
>>> locale.atof("3,1415926")
3.1415926000000001
If you don't want to mess with the locale, you 4 can of course do the formatting yourself. This 3 might serve as a starting point:
def formatFloat(value, decimals = 2, sep = ","):
return "%s%s%0*u" % (int(value), sep, decimals, (10 ** decimals) * (value - int(value)))
Note that 2 this will always truncate the fraction part 1 (i.e. 1.04999 will print as 1,04).
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.