Created
April 12, 2020 05:45
-
-
Save englandbaron/987d449ecd965b558b858e687b843b71 to your computer and use it in GitHub Desktop.
decimal caclculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: utf-8 | |
class calculator(object): | |
def __init__(self, scale): | |
self.scale = scale | |
def split(self, value): | |
INT = [] | |
FLOAT = [] | |
_mos = False | |
for v in value: | |
if v == '.': | |
_mos = True | |
continue | |
if _mos == False: | |
INT.append(v) | |
if _mos == True: | |
FLOAT.append(v) | |
return INT, FLOAT | |
def int_align(self, a, b): | |
if len(a) < len(b): | |
for i in range(len(b) - len(a)): | |
a.insert(0,'0') | |
else: | |
for i in range(len(a) - len(b)): | |
b.insert(0,'0') | |
a.reverse() | |
b.reverse() | |
def float_align(self, a, b): | |
if len(a) < len(b): | |
for i in range(len(b) - len(a)): | |
a.append('0') | |
else: | |
for i in range(len(a) - len(b)): | |
b.append('0') | |
a.reverse() | |
b.reverse() | |
def _add_calc(self, a , b): | |
result = [] | |
carry = False | |
for i in range(len(a)): | |
_tmp_result = int(a[i]) + int(b[i]) | |
if _tmp_result < 10: | |
result.append(str(_tmp_result)) | |
else: | |
result.append(str(_tmp_result - 10)) | |
if i < (len(a) - 1): | |
a[i+1] = str(int(a[i+1]) + 1) | |
else: | |
carry = True | |
return result, carry | |
def FLOATADD(self, a, b): | |
self.float_align(a,b) | |
result, carry = self._add_calc(a,b) | |
result.reverse() | |
return result, carry | |
def INTADD(self, a, b, float_carry): | |
self.int_align(a,b) | |
result = [] | |
result, carry = self._add_calc(a,b) | |
result.reverse() | |
if carry == True: | |
result.insert(0,'1') | |
if float_carry == True: | |
_float = ['1'] | |
self.int_align(result,_float) | |
result, carry = self._add_calc(result,_float) | |
result.reverse() | |
if carry == True: | |
result.insert(0,'1') | |
return result | |
def add(self, a, b): | |
a_int, a_demical = self.split(a) | |
b_int, b_demical = self.split(b) | |
# print("a: %s | %s " % (a_int, a_demical)) | |
# print("b: %s | %s " % (b_int, b_demical)) | |
# print("------------------------------------") | |
float_result, float_carry = self.FLOATADD(a_demical, b_demical) | |
int_result = self.INTADD(a_int,b_int,float_carry) | |
return "".join(int_result + ['.'] + float_result) | |
def sub(self, a, b): | |
pass | |
def multi(self, a, b): | |
pass | |
def sub(self, a, b): | |
pass | |
def division(self, a, b): | |
pass | |
if __name__ == '__main__': | |
a = "123.222" | |
b = "999999.9999999" | |
calc = calculator(scale="5") | |
print("%s + %s = %s" % (a,b,calc.add(a,b))) | |
# print(calc.sub(a,b)) | |
# print(calc.multi(a,b)) | |
# print(calc.division(a,b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment