Round float number in python could not work with some number

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)

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

``````
1 Like

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

1 Like

As long as we are using floating point numbers, this issue will still be there. See this: 14. Floating Point Arithmetic: Issues and Limitations â€” Python 2.7.18 documentation (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

Giulio

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

2 Likes