Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

RegularExpression to convert from Fraction to decimal

Status
Not open for further replies.

Tim8w

Programmer
Apr 8, 2003
44
US
I need a RegularExpression that can convert a string from a fraction or decimal like "1/2" or "0.5" to a decimal "0.5". It needs to handle both cases. Input can be either fractional or decimal, output must be decimal...
 
My initial reaction was that regular expressions were overkill for this, but I could see where they could be useful in checking for a valid string format:
Code:
    Public Function ConvertDecimalOrFractionString(ByVal s As String, ByRef value As Decimal) As Boolean
        Dim result As Boolean = True

        If (Regex.IsMatch(s, "\d+\.\d+")) Then 'Parameter has a decimal point
            result = Decimal.TryParse(s, value)
        ElseIf (Regex.IsMatch(s, "\d+/\d+")) Then 'Parameter is a fraction
            Dim ixOp As Integer = s.IndexOf("/")
            Dim numerator As Integer = Convert.ToInt32(s.Substring(0, ixOp))
            Dim denominator As Integer = Convert.ToInt32(s.Substring(ixOp + 1, s.Length - ixOp - 1))
            If (denominator <> 0) Then
                value = Convert.ToDecimal(numerator / denominator)
            Else
                result = False
            End If
        End If

        Return result
    End Function
 
Improved version. Plus the modified regular expression makes the leading zero optional for the decimal format:
Code:
        If (Regex.IsMatch(s, "\d*\.\d+")) Then 'Parameter has a decimal point
            result = Decimal.TryParse(s, value)
        ElseIf (Regex.IsMatch(s, "\d+/\d+")) Then 'Parameter is a fraction
            Dim numer As Integer
            Dim denom As Integer
            Dim digits() As String = s.Split("/")
            result = (Integer.TryParse(digits(0), numer) AndAlso Integer.TryParse(digits(1), denom) AndAlso denom > 0)
            If (result = True) Then value = Convert.ToDecimal(numer / denom)
        End If
 
Now only missing the case for "1 3/4" and "2" (No decimal)
 
Add a reference to the COM library Microsoft Script Control. Then cheat ...
Code:
[blue]    Private Function Fraction(ByVal strSource As String) As String
        Dim sc As New MSScriptControl.ScriptControl()
        Dim RunningTotal As Double
        Dim Component As String

        sc.Language = "VBScript"

        For Each Component In Split(TextBox1.Text, " ")
            RunningTotal = RunningTotal + sc.Eval(Component)
        Next

        Fraction = RunningTotal.ToString

    End Function[/blue]
 
I ended up using four different RegEx to catch all the cases:

Code:
sPattern = "((?<whole>\d+) (?<num>\d+)/(?<den>\d+))"    ' 1 1/2 case
regExp = New System.Text.RegularExpressions.Regex(sPattern, RegexOptions.Compiled)
m = regExp.Match(dgvc.Value)

If m.Success Then
    dDecValue = CInt(m.Groups("whole").Value) + CInt(m.Groups("num").Value) / CInt(m.Groups("den").Value)
Else
    sPattern = "((?<num>\d+)/(?<den>\d+))"              ' 3/4 case
    regExp = New System.Text.RegularExpressions.Regex(sPattern, RegexOptions.Compiled)
    m = regExp.Match(dgvc.Value)
    If m.Success Then
        dDecValue = CInt(m.Groups("num").Value) / CInt(m.Groups("den").Value)
    Else
        sPattern = "(?<dec>\d+\.?\d+)"                  ' 0.5 case
        regExp = New System.Text.RegularExpressions.Regex(sPattern, RegexOptions.Compiled)
        m = regExp.Match(dgvc.Value)
        If m.Success Then
            dDecValue = CDbl(m.Groups("dec").Value)
        Else
            sPattern = "(?<whole>\d+)"                  ' 2 case
            regExp = New System.Text.RegularExpressions.Regex(sPattern, RegexOptions.Compiled)
            m = regExp.Match(dgvc.Value)
            If m.Success Then
                dDecValue = CDbl(m.Groups("whole").Value)
            Else
                MsgBox("Error in value")
            End If
        End If
    End If
End If
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top