'Enumeration to hold the temp types
Enum TempUnits
Kelvins = 0
Celsius = 1
Fahrenheit = 2
End Enum
'Now the conversion function
Public Function TempConverter(ByVal InitialTemp As Double, ByVal ConvFrom As TempUnits, ByVal ConvTo As TempUnits) As Double
Dim Temp As Double
'First make sure they didnt enter same values for convert from & convert to
If ConvFrom = ConvTo Then
'Return initial value
Temp = InitialTemp
Else
Try
'Now decide what they want done
Select Case ConvFrom
'Convert from Kelvins
Case TempUnits.Kelvins
'To Celsius
If ConvTo = TempUnits.Celsius Then
'Celsius = Kelvin - 273.15
Temp = InitialTemp - 273.15
'To Fahrenheit
ElseIf ConvTo = TempUnits.Fahrenheit Then
Temp = (InitialTemp - 273.15) * 1.8 + 32.0#
End If
'Convert from Celsius
Case TempUnits.Celsius
'To Kelvins
If ConvTo = TempUnits.Kelvins Then
'Kelvin = Celsius + 273.15
Temp = InitialTemp + 273.15
'To Fahrenheit
ElseIf ConvTo = TempUnits.Fahrenheit Then
'degree F = degree C x 1.8 + 32.
Temp = InitialTemp * 1.8 + 32.0#
End If
'Convert from Fahrenheit
Case TempUnits.Fahrenheit
'To Celsius
If ConvTo = TempUnits.Celsius Then
'degree C = (degree F - 32.) / 1.8
Temp = (InitialTemp - 32.0#) / 1.8
'To Kelvins
ElseIf ConvTo = TempUnits.Kelvins Then
Temp = ((InitialTemp - 32.0#) / 1.8) + 273.15
End If
End Select
Catch ex As Exception
MessageBox.Show(ex.Message, "Conversion Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Temp = 0
End Try
End If
Return Temp
End Function