1024で割った結果が1024以上である度に単位を1つ上げるという簡単な手法。
(require 'cl)
(defun convert-file-size (size)
(loop with size-units = (list "B" "KB" "MB" "GB" "TB")
with first-unit = (car size-units)
with last-unit = (car (last size-units))
for unit in size-units
and new_size = size then (/ new_size 1024.0)
when (or (< new_size 1024.0) (equal unit last-unit))
if (equal unit first-unit) return (format "%.0f%s" new_size unit)
else return (format "%.1f%s" new_size unit)))
(convert-file-size 30) ; => "30B"
(convert-file-size 5000) ; => "4.9KB"
(convert-file-size 100000000) ; => "95.4MB"
(convert-file-size 10000000000000000.0) ; => "9094.9TB"
Byteのときは小数点以下を表示しないという処理のため少し冗長に。整数だとオーバフローする可能性があるので、その場合は少数を渡す工夫が必要。