0

I am very new to Python. I am learning basic stuff and stumbled at this.

Why is 5 in the decimal not rounding to the next higher decimal digit in this example below?

>>> round(2.67576,4)
2.6758
>>> round(2.67575,4)
2.6757

I was expecting that the answer to both the expressions would be the same, but they aren't

Chris
  • 29,127
  • 3
  • 28
  • 51
  • Briefly: 2.67575 is actually slightly less than that in the computer, so it rounds downward (rather than toward even, as `round` does when it the value is right in the middle). – TigerhawkT3 Feb 14 '19 at 07:32

1 Answers1

-2

The short answer is "floats are weird".

This isn't so much a Python issue as an issue with any system that uses binary floating point to represent a quantity. The nature of floats is non exact, which makes it alright for tracking continuous values where precision is desired and exactness is not essential. Floats are not suitable for the kind of exact arithmetic you're trying to perform here.

I would suggest you look to Python's standard 'decimal' module for exact numeric work.

https://docs.python.org/2/library/decimal.html

direvus
  • 362
  • 2
  • 6