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

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

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

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

Giulio

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