views:

232

answers:

2

I need to format an integer representation of bytes into something friendly, and I'm hoping that there's a utility function in Ruby or in Rails that will do that formatting for me (to perpetuate my laziness, of course.)

I'm looking for something that would look like:

format_bytes(1024)     -> "1 KB"
format_bytes(102400)   -> "1 MB"

Looks like there's some stuff in ActiveSupport to do it the other way around, but I haven't found a way to do it in this direction.

If there isn't one that exists, does anyone have a particularly elegant solution?

+7  A: 

Number to human size is what you're looking for.

require 'actionview'
include ActionView::Helpers::NumberHelper
number_to_human_size(123)                                          # => 123 Bytes
number_to_human_size(1234)                                         # => 1.2 KB
number_to_human_size(12345)                                        # => 12.1 KB
number_to_human_size(1234567)                                      # => 1.2 MB
number_to_human_size(1234567890)                                   # => 1.1 GB
number_to_human_size(1234567890123)                                # => 1.1 TB
number_to_human_size(1234567, :precision => 2)                     # => 1.18 MB
number_to_human_size(483989, :precision => 0)                      # => 473 KB
number_to_human_size(1234567, :precision => 2, :separator => ',')  # => 1,18 MB
mwilliams
Thanks! I was looking for this exact solution.
CalebHC
A: 

Accepted answer still work, but requires actionpack instead of actionview in newer rails.

require 'actionpack'
Tim Peters