Reason #120 •
April 30th, 2026
Presenting bytes with ActiveSupport's number_to_human_size
Humans do not think in raw byte counts. At least I do not. ActiveSupport's NumberHelper#number_to_human_size fixes that.
Ruby
include ActiveSupport::NumberHelper
number_to_human_size(1234)
# => "1.21 KB"
number_to_human_size(1_234_567)
# => "1.18 MB"
number_to_human_size(5_242_880)
# => "5 MB"
JavaScript
const numberToHumanSize = (bytes) => {
const units = ["Bytes", "KB", "MB", "GB", "TB"];
let value = bytes;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
return `${parseFloat(value.toPrecision(3))} ${units[index]}`;
};
numberToHumanSize(1234567);
// => "1.18 MB"
This helper pairs beautifully with ActiveSupport's numeric byte helpers like 5.megabytes, which means both the calculation and the presentation can stay readable.
History
number_to_human_size first appeared in Rails 0.12.0, released in 2005, after being moved over from the older TextHelper#human_size.
It joined ActiveSupport::NumberHelper after some refactoring in Rails 4.0.0, released in 2013.