# [Tutor] How to sort float number from big numbers to small numbers?

Steven D'Aprano steve at pearwood.info
Mon Sep 25 12:52:58 EDT 2017

```On Mon, Sep 25, 2017 at 03:34:05AM +0000, edmundo pierre via Tutor wrote:

> I am trying to sort float numbers input by an user from the bigger to
> smaller number. I do not know how to compare float numbers. Any ideas?
> Thank you!

If the numbers are provided by the user, they will be in the form of
strings, so you have to convert to float first:

# pretend these came from the user
a = '1.2'
b = '100.9'
c = '2.4'
alist = [a, b, c]
alist.sort()
print(alist)

will print the result:

['1.2', '100.9', '2.4']

which is not what you want. Instead, do this:

# pretend these came from the user
a = '1.2'
b = '100.9'
c = '2.4'
alist = [float(a), float(b), float(c)]
alist.sort()
print(alist)

which will print

[1.2, 2.4, 100.9]

Also, you can make a copy of the list using sorted() instead of sort():

alist = [float(a), float(b), float(c)]
print(sorted(alist))

Be warned: some numbers which can be written exactly in decimal, like
0.1, may sometimes appear ever-so-slightly "off" when you convert to a
float. This is not a bug, but an unfortunate side-effect of the way
computers do arithmetic in base 2 (binary). Feel free to ask if you