How to print human readable byte counts

I came across this morning, and having a few minutes, adapted the Java code to Julia:

Being relatively new to Julia, this code is a little clumsy, but I’m sure someone can improve it. If anyone wants to adapt it to support Zetta and Yotta byte values, please do.

1 Like

Here is a shorter version that is converted from a javascript stackoverflow answer

function format_bytes(bytes, decimals = 2)
    bytes == 0 && return "0 Bytes"
    k = 1024
    dm = decimals < 0 ? 0 : decimals
    sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
    i = convert(Int, floor(log(bytes) / log(k)))
    return string(round((bytes / ^(k, i)), digits=dm)) * " " * sizes[i+1];

Tested on Julia 1.3.1.

There is also this (used by @time etc, not exported):

julia> Base.format_bytes(13422449238)
"12.501 GiB"