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, rounded to 3 significant figures. See docs/COMMENTS.md.
Constant Summary collapse
- UNITS =
%w[KB MB GB TB PB EB].freeze
Class Method Summary collapse
-
.human_size(byte_count) ⇒ Object
Returns byte_count as a Finder-style human-readable string.
Class Method Details
.human_size(byte_count) ⇒ Object
Returns byte_count as a Finder-style human-readable string.
Humane::SizeFormatter.human_size(225_935) #=> "226 KB"
13 14 15 16 17 18 19 20 21 |
# File 'lib/humane/size_formatter.rb', line 13 def human_size(byte_count) return "Zero KB" if byte_count.zero? return (byte_count == 1) ? "1 byte" : "#{byte_count} bytes" if byte_count < 1000 exponent = [(Math.log(byte_count) / Math.log(1000)).to_i, UNITS.size].min value = byte_count / (1000.0**exponent) "#{format_significant(value, 3)} #{UNITS[exponent - 1]}" end |