As an extension
Imports System.Runtime.CompilerServices
Module UnitExtension
Public Enum Units
B = 0
KB = 1 'kilo
MB = 2 'mega
GB = 3 'giga
TB = 4 'tera
PB = 5 'peta
EB = 6 'exa
ZB = 7 'zetta
YB = 8 'yotta
'add new values as needed
Auto = -1
End Enum
'compute max value of enum
Private ReadOnly maxU As Integer = [Enum].GetValues(GetType(Units)).Cast(Of Integer)().Max
'kFactor should be set according to your use
'see
'http://physics.nist.gov/cuu/Units/prefixes.html
'and
'http://physics.nist.gov/cuu/Units/binary.html
Private ReadOnly Kfactor As Integer = 1024 'or 1000
<Extension()>
Public Function ToUnit(ByVal theNumberToConvert As Object, _
Optional ByVal precision As Integer = 0, _
Optional ByVal whichUnit As Units = Units.Auto) As String
Dim _aNumber As Double = CType(theNumberToConvert, Double) 'the number being converted
Dim _fmt As String = "n" & precision.ToString 'format string
Dim _unit As Integer
If whichUnit = Units.Auto Then 'auto unit
_unit = CInt(Math.Floor(Math.Log(_aNumber, Kfactor))) 'yes
If _unit > maxU Then '> max unit
_unit = maxU 'use max unit
End If
Else
_unit = whichUnit 'no, force unit
End If
Dim _numberOfUnits As Double = _aNumber / (Kfactor ^ _unit) 'calculate number of units
Return String.Format("{0} {1}", _numberOfUnits.ToString(_fmt), CType(_unit, Units))
End Function
End Module
edit:
An overload for unit to unit conversion
<Extension()>
Public Function ToUnit(ByVal theNumberToConvert As Object, _
fromUnit As Units, _
Optional ByVal precision As Integer = 0, _
Optional ByVal whichUnit As Units = Units.Auto) As String
Dim _aNumber As Double = CType(theNumberToConvert, Double) * (Kfactor ^ fromUnit) 'the number being converted
Dim _fmt As String = "n" & precision.ToString 'format string
Dim _unit As Integer
If whichUnit = Units.Auto Then 'auto unit
_unit = CInt(Math.Floor(Math.Log(_aNumber, Kfactor))) 'yes
If _unit > maxU Then '> max unit
_unit = maxU 'use max unit
End If
Else
_unit = whichUnit 'no, force unit
End If
Dim _numberOfUnits As Double = _aNumber / (Kfactor ^ _unit) 'calculate number of units
Return String.Format("{0} {1}", _numberOfUnits.ToString(_fmt), CType(_unit, Units))
End Function