Created
October 15, 2018 22:32
-
-
Save blessdyb/b6ea0ed0d968be338c404faf45de4282 to your computer and use it in GitHub Desktop.
Using decimal package to fix rounding discrepancy issue
This file contains 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
from decimal import Decimal, ROUND_HALF_UP | |
# https://docs.python.org/3/library/functions.html#round | |
# https://support.office.com/en-us/f1/topic/csh?HelpId=xlmain11.chm60075&NS=MACEXCEL&Version=90&Lcid=1033&UiLcid=1033&EntryPoint=True | |
def round_fixed(value, digit): | |
value_str = str(value) | |
value_dec = Decimal(value_str) | |
exp_unit = Decimal('0.1') ** digit | |
mini_unit = Decimal('0.1') ** (digit + 1) | |
if value_dec % exp_unit == (5 * mini_unit): | |
value_dec += mini_unit | |
result = Decimal(value_dec).quantize(exp_unit, rounding=ROUND_HALF_UP) | |
return float(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment