Friendly Byte Formatting in Rails
Asked Answered
G

2

17

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(1048576)  -> "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?

Gadoid answered 8/12, 2008 at 16:5 Comment(0)
U
44

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

require 'action_view'
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
Uncertain answered 8/12, 2008 at 16:30 Comment(2)
max value is number_to_human_size(999999999999999) # => "909 TB"Mcelroy
@Mcelroy I don't think that's true anymore: number_to_human_size(9999999999999999999999999999999999999999999999999999999999999999) => "8670000000000000000000000000000000000000000000 EB" I don't think there is a max anymoreJandel
T
0

Instead of action_view helpers you can use ActiveSupport::NumberHelper #number_to_human_size

include ActiveSupport::NumberHelper  

number_to_human_size(1048576) # => "1 MB"
Truth answered 24/4 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.