Class: PrettyBytes

Inherits:
Object
  • Object
show all
Defined in:
lib/pretty_bytes.rb,
lib/pretty_bytes/version.rb

Constant Summary collapse

VERSION =
"1.1.5"

Instance Method Summary collapse

Instance Method Details

#convert(num) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/pretty_bytes.rb', line 4

def convert(num)
  if num.is_a? Numeric
    neg = num < 0
   units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

   if neg
     num = -num
   end

   if num < 1
     return (neg ? '-' : '') + "#{num} B"
   end

   exponent = [(Math.log(num) / Math.log(1000)).floor, units.length - 1].min
   num = "%g" % (num.round(2) / (1000**exponent)).round(2)
   unit = units[exponent]

   return (neg ? '-' : '') + "#{num} " + unit

  else
   return "Expected a number"
 end
end