I had the same problem and I quickly came up with a simple solution using awk
's log()
function:
awk '
BEGIN {
split("B,kiB,MiB,GiB", suff, ",")
}
{
size=$1;
rank=int(log(size)/log(1024));
printf "%.4g%s\n", size/(1024**rank), suff[rank+1]
}
'
And the precision lost in using float numbers is not that bad since that precision will be lost anyways.