Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFormat a BIG number of bytes in KB, MB, GB, TB, etc. by using an array of postfixes
DescriptionThis example shows how to format a BIG number of bytes in KB, MB, GB, TB, etc. by using an array of postfixes in Visual Basic 6.
Keywordsformat, bytes, KB, MB, GB
CategoriesAPI, Files and Directories
 
Thanks to Dougal Morrison.

Unfortunately the StrFormatByteSize API function (click here for an example) uses long integers to store byte values so it can only handle up to 2,147,483,647 bytes or a bit less than 2 GB. Modern computers often work with values greater than 2 GB and in some cases more than 1 TB (1 terabyte = 1024 gigabytes).

The Numeric2Bytes function makes an array of the postfixes (MB, GB, etc.) for different powers of 1024 and then finds the one that is appropriate. It formats the value with two digits to the right of the decimal place, using the correct

 
' Returns string with binary notation of b bytes,
' rounded to 2 decimal places , eg
' 123="123 Bytes", 2345="2.29 KB",
' 1234567="1.18 MB", etc
' b : double : numeric to convert
Function Numeric2Bytes(ByVal b As Double)
Dim bSize(8) As String
Dim i As Integer

   bSize(0) = "Bytes"
   bSize(1) = "KB" 'Kilobytes
   bSize(2) = "MB" 'Megabytes
   bSize(3) = "GB" 'Gigabytes
   bSize(4) = "TB" 'Terabytes
   bSize(5) = "PB" 'Petabytes
   bSize(6) = "EB" 'Exabytes
   bSize(7) = "ZB" 'Zettabytes
   bSize(8) = "YB" 'Yottabytes

   b = CDbl(b) ' Make sure var is a Double (not just
       ' variant)
   For i = UBound(bSize) To 0 Step -1
      If b >= (1024 ^ i) Then
         Numeric2Bytes = CStr(Round(b / (1024 ^ i), 2)) & " " & _
             "" & bSize(i)
         Exit For
      End If
   Next
End Function
 
See also:

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated