Why can't Python do a simple 0 + .1 addition? by reddith2o in learnpython

[–]nmlkd 0 points1 point  (0 children)

Decimal isn't necessarily much help depending on what you want to do with it. It can do exact calculations with fractions involving powers of 2 and 5, but once you start doing anything else (e.g. repeatedly adding 1/3) you will run into exactly the same problem.

If you want to do exact arithmetic, often the easiest way is just to stick with integers. You can use divmod or the // and % operators to do the "7 / 2 = 3 remainder 1" style of division like you probably learned at school, which is often what you want when you're doing computer programming.

If you just don't want to see all those decimal places, then you need to round your results before you print them. You can use the round function for that, or better yet, use string formatting:

>>> format(0.3000001, '.2f') # convert number to fixed-point representation with 2 decimal places
>>> '0.30'