Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def format_bytes(n):
- units = ('', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB')
- base = 1024
- decrement_threshold = 0.2
- divisor_max = len(units) - 1
- exponent = math.log(n, base) if n > 0 else 0
- remainder = exponent % 1
- exponent = int(exponent) # implicit floor
- decrement = int(0 < remainder < decrement_threshold)
- divisor = max(0, exponent - decrement)
- divisor = min(divisor, divisor_max)
- quotient = int(n/(base**divisor)) # implicit floor
- unit = units[divisor]
- return "{} {}".format(quotient, unit)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement