评估记录表上的字符串,

时间:2019-04-19 10:07:50

标签: vb.net

如何使用vb评估记录表上的匹配项,我有这样的代码

Dim absenperintah As SqlCommand = New SqlCommand("Select * from mytable where kodetp ='109'", cekdata)

            absenperintah.CommandType = CommandType.Text
            cekdata.Open()
            Dim valuex = "500"
            Using cekbaca As SqlDataReader = 
            absenperintah.ExecuteReader(CommandBehavior.CloseConnection)
                If cekbaca.Read = True Then
                    Dim nilxbaca = cekbaca("rumus_k") --> record in the table is   1906650*(3.7/100) 
                    Dim nilmy = valuex + nilxbaca
                    Dim result = New DataTable().Compute(nilmy, Nothing)
                    MsgBox(result)
                End If
                cekbaca.Close()
            End Using
            cekdata.Close()

我得到的结果为185,070,546,结果应为= 70,564.55

如何从Dim nilHy = valuex + nilxbaca获得结果= 70,564.55

1 个答案:

答案 0 :(得分:0)

您的问题是您将这些数字声明为字符串,并且正在相应地对其进行计算。

您认为自己在做什么:

500 + 1906650*(3.7/100) = 70,564.55

如果将它们作为数字处理,它将执行数学运算并且您的计算将有效。

但是,您已经将这些值声明为字符串。因此,代码实际上是这样运行的:

"500" + "1906650*(3.7/100)" 'String concatenation. Not math.
5001906650*(3.7/100) = 185,070,546 

请尝试以下代码:

Dim absenperintah As SqlCommand = New SqlCommand("Select * from mytable where kodetp ='109'", cekdata)

absenperintah.CommandType = CommandType.Text
cekdata.Open()
Dim valuex = "500" 
Using cekbaca As SqlDataReader = 
      absenperintah.ExecuteReader (CommandBehavior.CloseConnection)
    If cekbaca.Read = True Then
        Dim nilxbaca = cekbaca("rumus_k") 'record in the table is   "1906650*(3.7/100)" 
        Dim nilmy = valuex & " + " & nilxbaca 'makes "500 + 1906650*(3.7/100)"
        'Note: your next line of code, DataTable.Compute() will evaluate a 
        ' (string) formula over several rows. 
        Dim result = New DataTable().Compute(nilmy, Nothing)
        'Based on this code here, you are only processing one row. 
        'Maybe .Compute() is totally unnecessary here.  
        'You would be better to say: result = 500 + nilxbaca
        ' or maybe declare valuex as integer, to help the compiler treat it like a number instead of a string.
        ' or maybe your original code did apply this formula over several rows.
        ' ... In that case, my example would fix your Compute() formula.

        MsgBox(result)
    End If
    cekbaca.Close()
End Using
cekdata.Close()