Last active
June 20, 2017 03:27
-
-
Save Wardrop/4952405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Formats the given byte value into a human readable form. | |
# | |
# Accepts four optional arguments that control the output format: | |
# as_bits: If true, converts the given byte value to bits and adjusts the suffix accordingly. Defaults to false. | |
# binary: If true, calculates order of magnitude as base 2 (binary) instead of base 10 (decimal). Defaults to true. | |
# full_suffix: If true, uses full suffix names such as "Megabyte", otherwise uses abbreviations like "MB" or "Mib". Defaults to false. | |
# precision: The number of decimal points to include in the output. Trailing zero's are removed. Defaults to 2. | |
def format_bytes(bytes, as_bits: false, binary: true, full_suffix: false, precision: 2) | |
suffixes = ['', 'Kilo', 'Mega', 'Giga', 'Tera', 'Peta', 'Exa', 'Zetta', 'Yotta'] | |
suffixes.map! { |v| v.empty? ? '' : v[0]+'ibi' } if binary | |
abbreviations = suffixes.map do |v| | |
if v.empty? | |
as_bits ? 'bits' : 'bytes' | |
else | |
v[0] + (as_bits ? 'b' : 'B') | |
end | |
end | |
base = 1000 | |
if binary | |
base = 1024 | |
abbreviations[1..-1].each { |v| v.insert(1,'i') unless v.empty? } | |
end | |
bytes *= 8 if as_bits | |
suffixes.each { |v| v << as_bits ? 'bits' : 'bytes' } | |
exponent = bytes.zero? ? 0 : Math.log(bytes, base).floor | |
suffix = full_suffix ? suffixes[exponent] : abbreviations[exponent] | |
value = sprintf("%g", (bytes.to_f / (base ** exponent)).round(precision)) | |
"#{value} #{suffix}" | |
end | |
# Examples | |
p format_bytes(2039495402, as_bits: true, binary: true) | |
p format_bytes(2039495402, as_bits: true, binary: false) | |
p format_bytes(2039495402, as_bits: false, binary: false) | |
p format_bytes(2039495402, as_bits: false, binary: true) | |
p format_bytes(2039495402, as_bits: true, binary: true, full_suffix: true) | |
p format_bytes(2039495402, as_bits: true, binary: false, full_suffix: true) | |
p format_bytes(2039495402, as_bits: false, binary: false, full_suffix: true) | |
p format_bytes(2039495402, as_bits: false, binary: true, full_suffix: true) | |
p format_bytes(96, as_bits: true, binary: true) | |
p format_bytes(96, as_bits: true, binary: false) | |
p format_bytes(96, as_bits: false, binary: false) | |
p format_bytes(96, as_bits: false, binary: true) | |
p format_bytes(96, as_bits: true, binary: true, full_suffix: true) | |
p format_bytes(96, as_bits: true, binary: false, full_suffix: true) | |
p format_bytes(96, as_bits: false, binary: false, full_suffix: true) | |
p format_bytes(96, as_bits: false, binary: true, full_suffix: true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment