Sep 8, 2018 · 1 min read
I noticed the same thing as Eric, and additional observation: rounding to a negative number of digits seems like it would be better to return an int instead. In that case, digits==0 is no longer a special case:
def round_decimal(x, digits = 0):
#casting to string then converting to decimal
x = decimal.Decimal(str(x)) #string in scientific notation for significant digits: 1e^x
string = ‘1e’ + str(-1*digits) if digits <= 0:
#rounding for integers
return int(x.quantize(decimal.Decimal(string), rounding=’ROUND_HALF_UP’))
else:
#rounding for floating point numbers
return float(x.quantize(decimal.Decimal(string), rounding=’ROUND_HALF_UP’))