>>> num = 4.123456
>>> round(num, 3) # expecting 4.123
4.1230000000000002
I'm expecting 4.123 as a result, Am I wrong?
>>> num = 4.123456
>>> round(num, 3) # expecting 4.123
4.1230000000000002
I'm expecting 4.123 as a result, Am I wrong?
This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic:
Yep, your expectations don't match the design intent of your tools.
Check out this section of the Python tutorial.
Using math.round
is actually pretty rare. if you're trying to display a number as a string to a certain precision, you might want something more like
>>> num = 4.123456
>>> print "%.3f" % num
4.123
You might be interested in the documentation on string formatting.
If you want to have an exact representation of your floating point number, you have to use decimal
.
Why do you care? (That's a serious question.)
The answer that you're getting is so close to 4.123
as to make no difference. It can't be exactly 4.123
, since there are only finitely many numbers (around 2**64
on a typical machine) that Python can represent exactly, and without going into detail about floating-point representations, it just so happens that 4.123
isn't one of those numbers. By the way, 4.1230000000000002
isn't one of the numbers that can be exactly represented, either; the actual number stored is 4.12300000000000022026824808563105762004852294921875
, but Python truncates the decimal representation to 17 significant digits for display purposes. So:
4.123
and what you're getting is so tiny as to make no real difference. Just don't worry about it.str
, or string formatting.decimal
module.Final note: In Python 3.x and Python 2.7, the repr
of a float has changed so that you will actually get 4.123
as you expect here.