Bah. One, final, 1.9-compatible post that also handles the edge case of 
values in the range 1000...1024 of a value correctly.

K = 2.0**10
M = 2.0**20
G = 2.0**30
T = 2.0**40
def nice_bytes( bytes, max_digits=3 )
  value, suffix, precision = case bytes
    when 0...K
      [ bytes, 'b', 0 ]
    else
      value, suffix = case bytes
        when K...M then [ bytes / K, 'kB' ]
        when M...G then [ bytes / M, 'MB' ]
        when G...T then [ bytes / G, 'GB' ]
        else            [ bytes / T, 'TB' ]
      end
      used_digits = case value
        when   0...10   then 1
        when  10...100  then 2
        when 100...1024 then 3
      end
      leftover_digits = max_digits - used_digits
      [ value, suffix, leftover_digits > 0 ? leftover_digits : 0 ]
  end
  "%.#{precision}f#{suffix}" % value
end

[ 1, 12, 123, 1022, 1024,
  1234, 12345, 123456, 2**19.99, 2**20,
  1234567, 12345678, 123456789,
  1234567890
].each{ |bytes| puts nice_bytes( bytes ) }

#=> 1b
#=> 12b
#=> 123b
#=> 1022b
#=> 1.00kB
#=> 1.21kB
#=> 12.1kB
#=> 121kB
#=> 1017kB
#=> 1.00MB
#=> 1.18MB
#=> 11.8MB
#=> 118MB
#=> 1.15GB
-- 
Posted via http://www.ruby-forum.com/.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to