I am trying again(!) to learn enough Python to be able to process a bunch of files, and have run into something I don't understand right at the beginning. I am using Python 2.5 IDLE on a WindowsXP machine, and going through examples given in a Python tutorial. My understanding is that the built-in round function is written round(variable, n) where variable is the number to be rounded and n is the desired number of digits after the decimal point. I get the following:

>>> x = -2.3
>>> x
-2.2999999999999998
>>> round (x, 2)
-2.2999999999999998
>>> round (x)
-2.0
>>> round (x, 1)
-2.2999999999999998

Does anyone have any ideas?

Thank you!

It's working, n isn't the amount of decimal points its the number being divided.
round(2.5, 5)
output = 2.5
round(2.8, 5)
output = 2.7999999999999998

round( x[, n])

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

Oops - maybe I responded too quickly. I just looked up the documentation again on built-in functions and found the above; so I think that my reading is the one intended here.

Mathematically, round(x, n) is the number of the form integer * (10**(-n)) which is closest to x. For example round(2.12345678, 3) is 2.123. Python prints 2.1230000000000002 because it uses a binary representation internally and 2.123 has an infinite number of binary digits, but it means 2.123. For example if I compute 1000 * round(2.12345678, 3) - 2123 , it prints 0.0

Thanks very much to both! Yes, I was aware of the fact that decimal fractions are in general not representable "exactly" as binary fractions; but I've been used to round-type functions using a process of adding an increment and truncating for display, thus giving the "exact" representation that some of us expect ... So thanks also for making me think about it again!

This question has already been answered. Start a new discussion instead.