将字节转换为 kb、mb、gb 等的 ActionScript 代码
我有一个实用程序函数,可以像 Windows 资源管理器一样以适当的形式显示文件大小,即;将其转换为最接近的 KB、MB、GB 等。我想知道我编写的代码是否正确,以及是否可以变得更简单。
我编写的函数如下:
public static function formatFileSize(bytes:int):String
{
if(bytes < 1024)
return bytes + " bytes";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Kb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Mb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Gb";
}
}
}
return String(bytes);
}
虽然它目前为我完成了工作,但我觉得它可以用更简单的方式编写,甚至可以优化。
提前致谢
I have a utility function that will display a filesize in an appropriate form like Windows Explorer does, i.e; convert it to nearest KB, MB, GB etc. I wanted to know if the code that i wrote is correct, and if it can be made simpler.
The function that i wrote is as follows :
public static function formatFileSize(bytes:int):String
{
if(bytes < 1024)
return bytes + " bytes";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Kb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Mb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Gb";
}
}
}
return String(bytes);
}
While it does the job for me at the moment, i feel it could be written in an even simpler way and maybe even optimized.
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种更简单的方法:
为了完整性,我将其包含到 yottabytes :)
Here's a simpler way of doing it:
I included it up to yottabytes for completeness :)
@J_A_X 有最好的方法来做到这一点,但是对于未来,我建议当您发现您有像您一样的嵌套
if...else...if
语句时尽早返回。@J_A_X has the best way to do this, however for the future, I suggest returning early when you find you have nested
if...else...if
statements like you have.