Skip to content

Instantly share code, notes, and snippets.

@sinchantsao
Last active January 17, 2021 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinchantsao/48aae9bcb7da1330c212ab5f3c01af3d to your computer and use it in GitHub Desktop.
Save sinchantsao/48aae9bcb7da1330c212ab5f3c01af3d to your computer and use it in GitHub Desktop.
how to round to 2 decimal ignoring any shit storage method in disk
"""
>>> round(2.5)
2
>>> round(3.5)
4
>>> round(4.5)
4
>>> round(1.555, 2)
1.55
>>> round(1.556, 2)
1.56
fees the brokers charging is rounded
due to the Floating-Point Arithmetic question, we actually will get the wrong allaways
so, the code piece was written for the question
"""
def round_(number, ndigists=2):
"""
desc:
number -> to rounding
ndigists -> how many digiest to retained
"""
value_str = str(number)
whole_part, decimal_part = map(lambda x:map(lambda _: int(_), list(x)),
value_str.split('.'))
whole_part_hold = len(whole_part)
decimal_part = decimal_part[:ndigists+1]
decimal_part_hold = len(decimal_part)
def addto(elements, position=-1):
if decimal_part_hold <= ndigists
return
if elements[position] > 9:
to_append, situ = elements[position]/10, elements[position]%10
elements[position] = situ
try:
elements[position-1] += to_append
except IndexError:
elements.insert(0, to_append)
addto.whole_part_hold += 1
addto(elements, position-1)
elif elements[position] > 4:
if (addto.whole_part_hold + addto.decimal_part_hold - abs(position)) < (addto.whole_part_hold + ndigists):
return
if addto.upgrade:
elements[position-1] += 1
addto(elements, position-1)
else:
return
else:
return
addto.upgrade = True
addto.whole_part_hold = whole_part_hold
addto.decimal_part_hold = decimal_part_hold
todo_alice = (whole_part + decimal_part)
addto(todo_alice, -1)
whole_part = ''.join(map(lambda _: str(_), todo_alice[:addto.whole_part_hold]))
decimal_part = ''.join(map(lambda _: str(_), todo_alice[addto.whole_part_hold: addto.whole_part_hold+ndigists]))
return float(whole_part + '.' + decimal_part[:ndigists])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment