I’m not sure what you mean; afaik, VB doesn’t have a Fraction type. But in general, you can get a decimal number by dividing the numerator by the denominator.

If you have a string that represents a fraction, e.g. “4/9″, you can split the string on the “/” character. You can then use CInt(str) to convert each string-as-number to an Integer (or CLng if you need a long), but make sure to call IsNumeric(str) on each string-as-number before you try to convert it, because CInt/CLng do not error out quietly.

If you have a string that contains one of the fractional special characters, e.g. “¾”, I think you’ll have to just manually do the conversion with a select statement or equivalent.

Public Function GetNumerator(ByVal x As Decimal, ByVal denominator As Integer) As Decimal
'discard whole number
x = x Mod 1
'get numerator
x = x * denominator
'round to whole number
Return Decimal.Round(x, 0)
End Function
Public Function GetGCF(ByVal x As Integer, ByVal x1 As Integer) As Integer
x = Math.Abs(x)
x1 = Math.Abs(x1)
If x = x1 Then Return x
If x > x1 Then
If x Mod x1 = 0 Then
Return x1
Else
For i As Integer = x1 - 1 To 1 Step -1
If x Mod i = 0 And x1 Mod i = 0 Then
Return i
End If
Next
End If
Else
If x1 Mod x = 0 Then
Return x
Else
For i As Integer = x - 1 To 1 Step -1
If x1 Mod i = 0 And x Mod i = 0 Then
Return i
End If
Next
End If
End If
End Function
Public Function GetRoundedFraction(ByVal d As Decimal, ByVal Maxd As Integer) As String
Dim Numerator As Integer = GetNumerator(d, Maxd)
Dim GCF As Integer = GetGCF(Numerator, Maxd)
If GCF = 0 Then Return "0"
Numerator = CInt(Numerator / GCF)
Dim Denominator As Integer = CInt(Maxd / GCF)
Return (Numerator & "/" & Denominator)
End Function

## Discuss This Question: 3 Replies