I'm trying to code a generic function to convert between filesizes, bytes to kb, gb to mb, etc...
The problem begins when "ToSize" value is lower than "FromSize", I don't get the correct values.
Someone can help me to fix the problems and maybe to simplify all the code?
#Region " Convert Between Sizes "
Enum FromSize As Long
bytes = 1L
kilobyte = 1024L
megabyte = 1048576L
gigabyte = 1073741824L
terabyte = 1099511627776L
petabyte = 1125899906842624L
End Enum
Enum ToSize As Long
bytes = 1L
kilobyte = 1024L
megabyte = 1048576L
gigabyte = 1073741824L
terabyte = 1099511627776L
petabyte = 1125899906842624L
End Enum
Private Function Size_To_Size(ByVal Size As Long, _
ByVal FromSize As FromSize, _
ByVal ToSize As ToSize, _
Optional ByVal decimals As Integer = 2 _
) As Double
Dim bytes As Double = Convert.ToDouble(Size * FromSize)
Dim Kbs As Double = bytes * FromSize.kilobyte
Dim mbs As Double = bytes * FromSize.megabyte
Dim gbs As Double = bytes * FromSize.gigabyte
Dim tbs As Double = bytes * FromSize.terabyte
Dim pbs As Double = bytes * FromSize.petabyte
If ToSize < FromSize Then
Select Case ToSize
Case ToSize.bytes : Return bytes
Case ToSize.kilobyte : Return Kbs.ToString("n" & decimals)
Case ToSize.megabyte : Return mbs.ToString("n" & decimals)
Case ToSize.gigabyte : Return gbs.ToString("n" & decimals)
Case ToSize.terabyte : Return tbs.ToString("n" & decimals)
Case ToSize.petabyte : Return pbs.ToString("n" & decimals)
Case Else : Return -1
End Select
ElseIf ToSize > FromSize Then
Select Case ToSize
Case ToSize.bytes : Return bytes
Case ToSize.kilobyte : Return (Kbs / ToSize.kilobyte / 1024L).ToString("n" & decimals)
Case ToSize.megabyte : Return (mbs / ToSize.megabyte / 1024L / 1024L).ToString("n" & decimals)
Case ToSize.gigabyte : Return (gbs / ToSize.gigabyte / 1024L / 1024L / 1024L).ToString("n" & decimals)
Case ToSize.terabyte : Return (tbs / ToSize.terabyte / 1024L / 1024L / 1024L / 1024L).ToString("n" & decimals)
Case ToSize.petabyte : Return (pbs / ToSize.petabyte / 1024L / 1024L / 1024L / 1024L / 1024L).ToString("n" & decimals)
Case Else : Return -1
End Select
Else ' ToSize = FromSize
Return Size.ToString("n" & decimals)
End If
End Function
#End Region
UPDATE:
This gives the correct result:
MsgBox(Size_To_Size(50, FromSize.gigabyte, ToSize.bytes).ToString("n2"))
' Result: 53,687,091,200
This DON'T gives the correct result:
msgbox(Size_To_Size(50, FromSize.gigabyte, ToSize.kilobyte).ToString("n2"))
' Result: 54.975.581.388.800,00
' Expected result: 52,428,800
' As shown here: http://www.t1shopper.com/tools/calculate/file-size/result/?size=50&unit=gigabytes