Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change my float into a two decimal number with a comma as a decimal point separator in python?

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?

like image 801
Hobhouse Avatar asked Oct 07 '09 09:10

Hobhouse


People also ask

How do you convert a float to two decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do you write a float value up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you convert a number with a comma to float?

To convert number strings with commas in Python Pandas DataFrame to float, we can use the astype method. to convert the values in the data frame df 's colname column to a float by removing the commas from the strings with str. replace .


3 Answers

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)
like image 99
Aaron Digulla Avatar answered Oct 25 '22 03:10

Aaron Digulla


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
like image 21
u0b34a0f6ae Avatar answered Oct 25 '22 02:10

u0b34a0f6ae


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).

like image 29
unwind Avatar answered Oct 25 '22 03:10

unwind