Wednesday, April 25, 2007

VBScript: Function Code to Convert Bytes to KB/MB/GB/TB

When querying for disk space sizes using WMI, it returns the numbers in bytes. These large numbers in bytes do not make much sense until they are converted into Kilobytes (KB), Megabyte (MB), Gigabyte (GB), or Terabyte (TB) and so on. Quite frequently I need to convert these sizes in bytes to KB/MB/GB/TB for better interpretation. I therefore created a quick VBScript function which I call inside VBScript code whenever I need to convert numbers in bytes to KB/MB/GB/TB.

Function ConvertSize(Size)
Do While InStr(Size,",") 'Remove commas from size
    CommaLocate = InStr(Size,",")
    Size = Mid(Size,1,CommaLocate - 1) & _
        Mid(Size,CommaLocate + 1,Len
(Size) - CommaLocate)
Loop

Suffix = " Bytes"
If Size >= 1024 Then suffix = " KB"
If Size >= 1048576 Then suffix = " MB"
If Size >= 1073741824 Then suffix = " GB"
If Size >= 1099511627776 Then suffix = " TB"

Select Case Suffix
    Case " KB" Size = Round(Size / 1024, 1)
    Case " MB" Size = Round(Size / 1048576, 1)
    Case " GB" Size = Round(Size / 1073741824, 1)
    Case " TB" Size = Round(Size / 1099511627776, 1)
End Select

ConvertSize = Size & Suffix
End Function

7 comments:

Sander said...

Thanks, just what I was looking for

DJ said...

Thanks, very useful. That Do While Instr Loop is sweet too.

GiZmO said...

It's a useful script, but since you're not really using the vars from the commaremoval-phase for anything you might as well replace the do-while with this line:
Size = Replace(Size,",","")

And be done with it... ;)

You might also want to save yourself from future headaches by performing a "VarType-check" on the result as the function would behave erratic with garbled input.

Anonymous said...

Thanks this was very helpful

treehead said...

' Here's the function after GiZmO's suggestions:
Function ConvertSize(Size)
Size = CSng(Replace(Size,",",""))

If Not VarType(Size) = vbSingle Then
ConvertSize = "SIZE INPUT ERROR"
Exit Function
End If

Suffix = " Bytes"
If Size >= 1024 Then suffix = " KB"
If Size >= 1048576 Then suffix = " MB"
If Size >= 1073741824 Then suffix = " GB"
If Size >= 1099511627776 Then suffix = " TB"

Select Case Suffix
Case " KB" Size = Round(Size / 1024, 1)
Case " MB" Size = Round(Size / 1048576, 1)
Case " GB" Size = Round(Size / 1073741824, 1)
Case " TB" Size = Round(Size / 1099511627776, 1)
End Select

ConvertSize = Size & Suffix
End Function

Anonymous said...

treeheads version works just fine.

I would only recommend to move the line:
Size = CSng(Replace(Size,",",""))
after parameter type check:

If Not VarType(Size) = vbSingle ...

Without this the function will fail if the parameter is not valid number

Thanks for sharing the code

Michael Progrmmer said...


I had been working out on the script for the whole day and I cant manage to get through until I found the script on this site.

Thank you very much for the useful script...