SHARE
TWEET

Formatting bytes intelligently with Python

a guest Jan 28th, 2015 275 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import math
  2.  
  3. def format_bytes(n):
  4.  
  5.     units = ('', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB')
  6.     base = 1024
  7.     decrement_threshold = 0.2
  8.     divisor_max = len(units) - 1
  9.  
  10.     exponent = math.log(n, base) if n > 0 else 0
  11.     remainder = exponent % 1
  12.     exponent = int(exponent)  # implicit floor
  13.  
  14.     decrement = int(0 < remainder < decrement_threshold)
  15.     divisor = max(0, exponent - decrement)
  16.     divisor = min(divisor, divisor_max)
  17.  
  18.     quotient = int(n/(base**divisor))  # implicit floor
  19.     unit = units[divisor]
  20.     return "{} {}".format(quotient, unit)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top