2010-01-29 64 views
2

我想出了以下解決方案來格式化一個整數(字節大小的文件)。有沒有更好/更短的解決方案?我特別不喜歡float_as_string()部分。簡單的方法來以可讀的方式格式化字節大小?

human_filesize(Size) -> 
    KiloByte = 1024, 
    MegaByte = KiloByte * 1024, 
    GigaByte = MegaByte * 1024, 
    TeraByte = GigaByte * 1024, 
    PetaByte = TeraByte * 1024, 

    human_filesize(Size, [ 
    {PetaByte, "PB"}, 
    {TeraByte, "TB"}, 
    {GigaByte, "GB"}, 
    {MegaByte, "MB"}, 
    {KiloByte, "KB"} 
    ]). 


human_filesize(Size, []) -> 
    integer_to_list(Size) ++ " Byte"; 
human_filesize(Size, [{Block, Postfix}|List]) -> 
    case Size >= Block of 
    true -> 
     float_as_string(Size/Block) ++ " " ++ Postfix; 
    false -> 
     human_filesize(Size, List) 
end. 

float_as_string(Float) -> 
    Integer = trunc(Float), % Part before the . 
    NewFloat = 1 + Float - Integer, % 1.<part behind> 
    FloatString = float_to_list(NewFloat), % "1.<part behind>" 
    integer_to_list(Integer) ++ string:sub_string(FloatString, 2, 4). 

編輯:修正了圓() - > TRUNC()

+1

你不應該使用trunc()而不是round()嗎? – 2010-01-29 17:47:49

回答

5
human_filesize(Size) -> human_filesize(Size, ["B","KB","MB","GB","TB","PB"]). 

human_filesize(S, [_|[_|_] = L]) when S >= 1024 -> human_filesize(S/1024, L); 
human_filesize(S, [M|_]) -> 
    io_lib:format("~.2f ~s", [float(S), M]). 

注意它返回一個iolist。如果你需要一個字符串,你可以將其轉換爲二進制文件並將其轉換爲字符串。

+0

謝謝,這看起來不錯。 – ZeissS 2010-02-01 11:57:44

相關問題