python convert a list of float to string

Niebieski picture Niebieski · May 2, 2014 · Viewed 29.2k times · Source

I have a list of floats in Python and when I convert it into a string, I get the follwoing

[1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]

These floats have 2 digits after the decimal point when I created them (I believe so),

Then I used

str(mylist)

How do I get a string with 2 digits after the decimal point?

======================

Let me be more specific:

I want to get something like "[1883.95, 1878.33, 1869.43, 1863.40]"

I need to some string operation afterwards. For example +="!\t!"

I want the end result to be a string and I want to keep the separators.

Of course we all know how to do it in a loop, but hopefully someone can come up a very smart&elegant way to it.

inspired by @senshin the following code works for example, but I think there is a better way

msg = "["
for x in mylist:
    msg += '{:.2f}'.format(x)+','
msg = msg[0:len(msg)-1]
msg+="]"
print msg

Thanks!

Answer

senshin picture senshin · May 2, 2014

Use string formatting to get the desired number of decimal places.

>>> nums = [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
>>> ['{:.2f}'.format(x) for x in nums]
['1883.95', '1878.33', '1869.43', '1863.40']

The format string {:.2f} means "print a fixed-point number (f) with two places after the decimal point (.2)". str.format will automatically round the number correctly (assuming you entered the numbers with two decimal places in the first place, in which case the floating-point error won't be enough to mess with the rounding).