以人类可读的方式格式化字节大小的更简单方法?
我想出了以下解决方案来格式化整数(文件的字节大小)。有更好/更短的解决方案吗?我特别不喜欢 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).
编辑:修复了错误 round() ->截断()
I came up with the following solution to format an integer (bytesize of a file). Is there any better/shorter solution? I esacially don't like the float_as_string()
part.
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).
Edit: Fixed bug round() -> trunc()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,这会返回一个 iolist。如果需要字符串,可以将其转换为二进制,然后再将其转换为字符串。
Note that this returns an iolist. If you need a string, you can convert that to binary and that to string.