Question
Why am I seeing extra decimal places being outputted when doing basic arithmetic in Python, and how can I round those numbers?
Answer
A loss in precision often occurs when doing floating point arithmetic. This is due to the nature of floating point numbers and how they are stored in the machine (see here for more details). For example, the below will print 0.44999999999999996
instead of 0.45
:
sum = 0.1 + 0.35
print(sum) # 0.44999999999999996
A couple ways you could round your final answer is to use the built-in round()
function or to format the answer as a string using the string method .format()
:
print(round(sum, 2)) # 0.45
print('{:.2f}'.format(sum)) # 0.45