18

I have a float: 1.2333333

How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Hobhouse
  • 15,463
  • 12
  • 35
  • 43

3 Answers3

16

To get two decimals, use

'%.2f' % 1.2333333

To get a comma, use replace():

('%.2f' % 1.2333333).replace('.', ',')

A second option would be to change the locale to some place which uses a comma and then use locale.format():

locale.setlocale(locale.LC_ALL, 'FR')
locale.format('%.2f', 1.2333333)
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
8

The locale module can help you with reading and writing 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
u0b34a0f6ae
  • 48,117
  • 14
  • 92
  • 101
2

If you don't want to mess with the locale, you can of course do the formatting yourself. This 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 this will always truncate the fraction part (i.e. 1.04999 will print as 1,04).

unwind
  • 391,730
  • 64
  • 469
  • 606