str to float (rounded)

Nader n.emami at gmail.com
Tue Jun 10 17:11:32 CEST 2008


On Jun 10, 4:30 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Nader wrote:
> > Hello,
>
> > I have a list of tuple with strin elements. These elements are number,
> > but they are save as string. Now I will change the string to number
> > which will be rounded. An example will make it more clear.
>
> > t = [('35.757', '-0.239'), ('33.332', '-2.707'), ('33.640', '-2.423')]
>
> > And I will have the next list:
>
> > t = [(35.76, -2.24), (33.33, -2.71), (33.64, -2.42)]
>
> > The elements of tuple are not more as string.
>
> > Would somebody tell me how I can do that?
>
> use
>
> float("123.45")
>
> to convert a string to a float.
>
> Of course you need to do that on all your elements above by e.g. a
> list-comprehension.
>
> Diez

If I do the next :

 t1 = [(round(float(x),1), round(float(y),2)) for x, y in t]

I get the long float as :

[(35.799999999999997, -0.23999999999999999), (33.299999999999997,
-2.71), (33.600000000000001,-2.4199999999999999)]

But I would have a float with 2 decimal numbers.





More information about the Python-list mailing list