Round float number in python could not work with some number


#1

When I use python to round a list of float number. why the last two number in the list blow are still very long number, while the first number in the list works. Thanks for any shared knowledge

listnum = ( 10.4045607172, 9.94684017538, 8.55713882428)
round(listnum,2)
return
(10.4, 9.949999999999999, 8.560000000000001)


#2

Hmm, odd… Must be something we’re not understanding…

listnum = [10.4045607172, 9.94684017538, 8.55713882428]

print [round(num,2) for num in listnum]
>>>[10.4, 9.949999999999999, 8.560000000000001]

rounded=[]
for num in listnum: rounded.append(round(num,2))
print rounded
>>>[10.4, 9.949999999999999, 8.560000000000001]

for num in listnum:
    rnd=(round(num,2))
    print rnd
>>>10.4
   9.95
   8.56

#3

It has something to do with how the numbers are stored in memory. What you are doing is correct. As @Helvetosaur shows if you store them in a list you can expect this type of outcome. I’ve just search for a bit and you can use the decimal module.

import decimal
listnum = ( 10.4045607172, 9.94684017538, 8.55713882428)

listout = []
for value in listnum:
    d = decimal.Decimal(value)
    decimal.getcontext().prec = 3
    listout.append(d*1)

print listout
# Output : [Decimal('10.4'), Decimal('9.95'), Decimal('8.56')]

if you just want it for visualisation purposes you can use this:

listnum = ( 10.4045607172, 9.94684017538, 8.55713882428)

listout = []
for value in listnum:
    print("Number: {:.2f}".format(value))


#4

I think it does actually round the numbers despite it not looking like it did. See this:

That said, “normal” Python does not display the same behaviour (running Python 2.7 in Sublime Text 2):

Either way, it looks like you should be good to use the rounded values…

/Anders


(Giulio Piacentino) #5

As long as we are using floating point numbers, this issue will still be there. See this: https://docs.python.org/2.7/tutorial/floatingpoint.html#representation-error (and see the difference once you choose 2.6, for example, in the last sentence.

The way the almost-perfect number will be represented might affect the way we think about it, but the number is simply not there in the floating number representation. The best way would be using rounding when we mean rounding to the number at an interval, and the format function when we need the display.

You guys had all this figured out :slight_smile:

Giulio

Giulio Piacentino
for Robert McNeel & Associates
giulio@mcneel.com