Description
[*:2derlw7z]Converts from a specified size (in byes) to an equivalent value in byte(s)/KB/MB/GB/TB - uses the most appropriate unit.
Download
autoByteFormat.zip
Requirements
AHK v1.0.48+
Functions
autoByteFormat(size, decimalPlaces = 2)
Converts from a specified size (in byes) to an equivalent value in byte(s)/KB/MB/GB/TB - uses the most appropriate unit.
See the wiki page for file size for details on what each of these units are. This function uses the "Binary Measurement" (see the conversion table for details).
Parameters
size - integer size (in bytes)
decimalPlaces - decimal places to round result. If return is in bytes, no rounding is done, since it's an integer.
ReturnValue
Formatted size in bytes(s)/KB/MB/GB/TB
Format:
if size = 1 (byte)
returns "1 byte"
else if size < 1KB (1024 bytes)
returns "X bytes"
else if size < 1MB (1024 * 1024 bytes)
returns "X KB"
else if size < 1GB (1024 * 1024 * 1024 bytes)
returns "X MB"
else if size < 1TB (1024 * 1024 * 1024 * 1024 bytes)
returns "X GB"
else
returns "X TB"
"X" is the rounded value (to the specified decimal places), in the appropriate units.
Remarks
Size MUST be greater than or equal to zero.
Code
;converts Size (in bytes) to byte(s)/KB/MB/GB/TB (uses best option) ;decimalPlaces is the number of decimal places to round autoByteFormat(size, decimalPlaces = 2) { static size1 = "KB", size2 = "MB", size3 = "GB", size4 = "TB" sizeIndex := 0 while (size >= 1024) { sizeIndex++ size /= 1024.0 if (sizeIndex = 4) break } return (sizeIndex = 0) ? size " byte" . (size != 1 ? "s" : "") : round(size, decimalPlaces) . " " . size%sizeIndex% }
Example
1MB := 1024 * 1024 1@26MB := 1.26 * 1024 * 1024 1000@27GB := 1000.27 * 1024 * 1024 * 1024 17@28TB := 17.28 * 1024 * 1024 * 1024 * 1024 Bytes = (LTrim 0 1 2 100 1024 1500 %1MB% %1@26MB% %1000@27GB% %17@28TB% ) Loop, Parse, Bytes, `n { MsgBox, % A_LoopField " bytes = " autoByteFormat(A_LoopField) }
How to use
Extract the zip's contents to a library folder for automatic inclusion - StdLib compliant.
A copy of the above example can be found in the "Func Examples" folder.
Download autoByteFormat function