Skip to content

Instantly share code, notes, and snippets.

@wconrad
Created May 28, 2019 20:03
Show Gist options
  • Save wconrad/096ce45a0ba010a00dcdf3ef0152474f to your computer and use it in GitHub Desktop.
Save wconrad/096ce45a0ba010a00dcdf3ef0152474f to your computer and use it in GitHub Desktop.
Convert byte counts to SI units
class SiByteCount
def initialize(n)
@n = n
end
def to_s
n = signif(@n, 3)
UNITS.each do |coef, abbrev|
if n >= coef
n = n / coef unless coef.infinite?
return "#{remove_trailing_decimal_zeros(n)} #{abbrev}"
end
end
end
private
UNITS = [
[1E12, "TB"],
[1E9, "GB"],
[1E6, "MB"],
[1E3, "kB"],
[-Float::INFINITY, "B"],
]
private_constant :UNITS
# From https://stackoverflow.com/a/44891822/238886
def signif(f, significant_digits)
return 0 if f.zero?
f.round(-(Math.log10(f).ceil - significant_digits))
end
def remove_trailing_decimal_zeros(n)
n
.to_s
.gsub(/(\.\d*)0+$/, '\1')
.gsub(/\.$/, "")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment