David Hoelscher
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’))
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade