0

I have been recently trying to make a calculator in python and added floating points in it but unfortunately it gives me for this simple code

print(0.1 + 0.2)

out put

0.30000004

I have searched a lot for it in stackoverflow but I keep getting questions about why it happened and not how to fix it. Edit: a lot of people have been recently giving me private feedbacks about this already exists I appreciate that to improve stackoverflow but there are no questions most of them are explanations about why it is happening and not how to fix it. some of the feedbacks have got even questions that are not python

Tiger Lion
  • 35
  • 1
  • 5

6 Answers6

4

you can try any of the follow methods which is conventional for you

#for two decimal places use 2f, for 3 use 3f
val = 0.1 + 0.2
print(f"val = {val:.2f}")

#output | val = 0.30

#or else 
print(round(val,2))

#output | val = 0.30
vishal
  • 462
  • 1
  • 5
  • 12
2

You can use the decimal built-in module with strings and make your own methods:

from decimal import Decimal
def exact_add(*nbs):
    return float(sum([Decimal(str(nb)) for nb in nbs]))

exact_add(0.1, 0.2)
# > 0.3
Whole Brain
  • 2,097
  • 2
  • 8
  • 18
1

I think the recommended way to resolve this is to determine a number of decimal places you want to consider and round to that using the built-in round function. Say you want to use 5 decimal places, you could do:

ans = 0.1 + 0.2
print(ans)    # 0.30000004
round(ans,5)
print(ans)    # 0.3

Note that round also gets rid of extra zeroes in the end. If you round 0.333333333333 to 5 decimals it will return 0.33333, but rounding 0.30000000004 returns 0.3.

fravolt
  • 2,565
  • 1
  • 4
  • 19
1

This has nothing to do with python, but with the way floating point values are represented on your machine. The way floating point works is the same for all languages, and it can potentially introduce rounding errors. This link shows you exactly why you get this error.

Just reduce the number of visible digits and you'll be fine. Just now that all computers and calculators have limited space for numbers, and all of them are prone to rounding errors.

1

You can use:

a = 0.1 + 0.2
a = round(a, 2)
print(a)
Output: 0.3
Huzaifa Arshad
  • 143
  • 3
  • 14
1

use round() syntax to get rid of excessive number of zeros. '''

a = 0.1
b = 0.2
c = a + b 
answer = round(c,3)   # here 3 represents the number of digits you want to round
print(answer)    

''' and incase you want more clarification on round() syntax just visit this link once: https://www.bitdegree.org/learn/python-round

smit patel
  • 23
  • 5