Class: Humane::SizeFormatter
- Inherits:
-
Object
- Object
- Humane::SizeFormatter
- Defined in:
- lib/humane/size_formatter.rb
Overview
Formats byte counts the way Finder does: 1000-based math, capitalized unit labels.
Constant Summary collapse
- UNITS =
%w[B KB MB GB TB PB EB].freeze
Instance Method Summary collapse
-
#string(from_byte_count:) ⇒ Object
Returns from_byte_count as a Finder-style human-readable string.
Instance Method Details
#string(from_byte_count:) ⇒ Object
Returns from_byte_count as a Finder-style human-readable string.
9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/humane/size_formatter.rb', line 9 def string(from_byte_count:) return "#{from_byte_count} B" if from_byte_count < 1000 exponent = [(Math.log(from_byte_count) / Math.log(1000)).to_i, UNITS.size - 1].min rounded = (from_byte_count / (1000.0**exponent) * 10).round / 10.0 if rounded < 10 format("%.1f %s", rounded, UNITS[exponent]) else format("%.0f %s", rounded, UNITS[exponent]) end end |