user3839017
user3839017

Reputation: 9

Fractional Number.

how to fix this error. . when user input whole number and multipy it there's no problem in this part of my code

but when user input a fractional number(negative or positive) like "1/2,-2/3 ETC" there is an error

the error is pointing in: new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)

Error Message: Conversion from string "1/2" to type 'Double' is not valid.

view plaincopy to clipboardprint? Dim new1, new2, new3, new4, new5, new6, add1, add2, minus1 As Double

    new1 = CDbl(txta1.Text) * CDbl(txtb2.Text) * CDbl(txtc3.Text)  
    new2 = CDbl(txta2.Text) * CDbl(txtb3.Text) * CDbl(txtc1.Text)  
    new3 = CDbl(txta3.Text) * CDbl(txtb1.Text) * CDbl(txtc2.Text)  

    new4 = CDbl(txtc1.Text) * CDbl(txtb2.Text) * CDbl(txta3.Text)  
    new5 = CDbl(txtc2.Text) * CDbl(txtb3.Text) * CDbl(txta1.Text)  
    new6 = CDbl(txtc3.Text) * CDbl(txtb1.Text) * CDbl(txta2.Text)  

Upvotes: 1

Views: 1627

Answers (2)

Mike Meinz
Mike Meinz

Reputation: 506

"1/2" is a string and must be parsed and converted into a numeric by your code.

Here is an example. For use with simple fractions (as shown in your example), decimals and negative numbers.

Note: You should add error checking. For brevity, I did not include any error checking.

    Dim strInput As String = "-1/2"
    Dim dblValue As Double = Nothing

    If strInput.Contains("/") Then ' A fraction
        Dim strArray() As String = strInput.Split(CChar("/"))
        dblValue = CDbl(strArray(0)) / CDbl(strArray(1))
    Else
        dblValue = CDbl(strInput)
    End If
    Console.WriteLine(dblValue)

Upvotes: 2

Christian Sauer
Christian Sauer

Reputation: 10889

Please activate Option strict ON, which will help you to prevent rookie mistakes like trying to use a textfield like txta1.text as a number: http://support.microsoft.com/kb/311329 You have to try to parse a value from text to a number like so:

Dim number1 As Double

If Double.TryParse(txta1.Text, number1) Then
 // do something
Else
   Console.WriteLine("{0} is outside the range of a Double.", _
                   value)
// report error
End If

Otherwise it is very hard to debug your code. As to fractions: I would be very hard to parse a fraction reliably by hand. I would somethink prebuild, like a mathematic expression library. Take a look: https://ncalc.codeplex.com/

Upvotes: 5

Related Questions