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...

Recommended Answers

All 3 Replies

can u explain further .. where are you using this?? what appliction some.. screens or code?

sandeepparekh9,
I have a DataGridView where the user can enter either fractional info like "1 1/2", "3/4", etc. or decimal values lime "1.5", 0.75", etc. The problem is that I need the data stored as decimal...

I ended up using four different RegEx to catch all the cases:

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.