Skip to content

Instantly share code, notes, and snippets.

@jskherman
Created February 11, 2022 16:29
Show Gist options
  • Save jskherman/ab49d1ace468d0c2278f336ca943968b to your computer and use it in GitHub Desktop.
Save jskherman/ab49d1ace468d0c2278f336ca943968b to your computer and use it in GitHub Desktop.
Function for rounding up numbers in Python
def round_up(n, decimals=0):
# Move significant decimal digits to the left of the decimal point
multiplier = 10 ** decimals
# Truncate the unneeded digits on the right of the decimal point
sig_digits = n * multiplier // 1
# Determine whether to round up or round down
# Return 1 if the tenth digit is greater than or equal to 5,
# else return 0 if less than 5
carry = int(((n * multiplier) % 1) >= 0.5)
# Add the 1 or 0 to the significant digit in the ones place
# and return to the digits to their original place values
return ((sig_digits + carry) / multiplier)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment