开发者

Displaying filesize on the user interface

开发者 https://www.devze.com 2023-02-09 11:03 出处:网络
I have been using following function to display the file size in bytes in more readable uable friendly on the user interface.

I have been using following function to display the file size in bytes in more readable uable friendly on the user interface.

function bytesToSize(bytes, precision)
{  
   var kilobyte = 1024;
   var megabyte = kilobyte * 1024;
   var gigabyte = megabyte * 1024;
   var terabyte = gigabyte * 1024;
   if ((bytes >= 0) && (bytes < kilobyte)) {
       return bytes + ' B';
   } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
       return (bytes / kilobyte).toFixed(precision) + ' KB';
   } else if ((bytes >= megabyte) &开发者_高级运维amp;& (bytes < gigabyte)) {
       return (bytes / megabyte).toFixed(precision) + ' MB';
   } else if ((bytes >= gigabyte) && (bytes < terabyte)) {
       return (bytes / gigabyte).toFixed(precision) + ' GB';
   } else if (bytes >= terabyte) {
       return (bytes / terabyte).toFixed(precision) + ' TB';
   } else {
       return bytes + ' B';
   }
}

However the problem is that it shows X KB, X MP ..etc (rounding the results to display on UI) and not able to show X.Y or say X,Y. After this thing thing came to my mind i was more confused and i started looking around the systems for how they show it on there UI. following are some of them,

  1. FileZill : XXX,XXX,XXX bytes (while uploading)
  2. Windows Explorer : XXX, XXX KB (in details view)

Now all these brought me to new level of confusion, as the size displayed on the UI using above function is not really precise imagine file size in GB's which is incorrectly displayed to user.

Please let know in which format this data should be displayed to the users to be more useful at the same time more accurate. Also real estate is expensive in today's complicated web pages which also needed to be considered.


For a quick overview I like the file size format xxx.x fooB where foo the biggest applicable of T, G, M, k (or empty).

That is, divide numBytes by 1024 until it's < 1000 using floating point arithmetic. Remember how often you divided, convert that to the according foo.

Of course you might want to consider other formats for detailed file size information.

0

精彩评论

暂无评论...
验证码 换一张
取 消