HotKeyIt wrote:Here is one written in AHK.
Advantages: no dependencies, faster, keeps dot '.' as comma separator instead using locale (e.g. ',' in german).
Thanks for sharing,
HotKeyIt
One may simply use StringReplace to rectify the locale problem.
I tried your code and like to share my observations.
1)
If (bytes>1024) should be
If (bytes>1023).
2) Maximum format-able bytes is 0xFFFFFFFFFFFFFFFF ( 7.99 EB ). The extra ZB,YB seems redundant ( does not hurt, though )
3)
FormatByteSize( 0xFFFFFFFF ) should return
3.99 GB but rounds the result to
4.00 GB owing to the default FloatFormat of
0.6
4)
FormatByteSize( 1024*1023 ) returns
1023 KB, whereas StrFormatByteSize64A() returns a more readable
0.99 MB.
The advantages of WinAPI
Shlwapi\StrFormatByteSize64A():
1) High Precision. 0xFFFFFFFFFFFFFFFF will be correctly formatted as
7.99 EB, but with AHK's highest precision of 15 digits, incorrect rounding occurs above
4.00 PB.
2) It formats the result to fit a common width by losing decimal places. This is aesthetically good on a GUI.
Example:
390 MB
93.2 MB
74.3 KB
41.8 KB
67.6 KB
7.61 KB
Here is my attempted native code:
FormatBytesEx()
Note: Precision is lost somewhere above 4.00 PB
Algorithm:
1) When bytes < 1000, return ( bytes . " bytes" ).
2) Return string
will not contain more than 3 digits ( irrespective of a period ).
3) Return string may have 1 decimal period, only when required.
Code: Select all
FormatBytesEx( Bytes ) { ; By SKAN, http://ahkscript.org/boards/viewtopic.php?p=18352#p18352
Static B1 := "KB", B2 := "MB", B3 := "GB", B4 := "TB", B5 := "PB", B6 := "EB"
IfLess, Bytes, 1000, Return Bytes + 0 " bytes"
AFF := A_FormatFloat
SetFormat, FloatFast, 0.15
While ( FL>3 or FL="" ) {
FBytes := Bytes / ( 1024 ** ( IX := A_Index ) )
StringSplit, F, FBytes, .
FL := StrLen( F1 )
}
SetFormat, FloatFast, %AFF%
Return F1 ( FL<3 ? "." SubStr( F2, 1, 3-FL ) : "" ) " " B%IX%
}
Simple test
FormatBytes() vs
FormatBytesEx() vs
FormatByteSize().
Code: Select all
A := "0xF"
Loop 15
R .= FormatBytes( A .= "F" ) "`t" FormatBytesEx( A ) "`t" FormatByteSize( A + 0 ) "`n"
MsgBox % R
Result: