I'm new to Python and I am having problems with floating point arithmetic. From what I understand, floating point arithmetic in Python generates binary approximations of decimal values and we deal with floating point values either by using the round() function, string formatting methods or the decimal.Decimal class.
However all of these require constantlly writing round(), decimal.Decimal() or string formatting methods during calculations. Is there a way to modify the preexisting float class in a particular program so that all calculations as well as storage of float values take place after rounding to a certain number of decimal places? Alternatively, can we create a new class to do this?
I have tried the second method and my code is:
class Float(float):
def count_decimal_places(float_num):
if type(float_num) == int:
return 0
return len(str(float_num).split('.')[1])
def __add__(self, other):
return round(self +other, max(count_decimal_places(self), count_decimal_places(other)))
This should return 3 + -1.6 as 1.4 and not 1.399999999998. However the above code doesn't work either.