SHOW:
|
|
- or go back to the newest paste.
1 | import math | |
2 | ||
3 | def format_bytes(n): | |
4 | ||
5 | units = ('', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB') | |
6 | base = 1024 | |
7 | - | decrement_threshold = 0.1 |
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) |