vb.net变量计算不正确的值

时间:2016-04-05 13:30:14

标签: vb.net

我在vb.net中运行此代码:

Dim sub_total as Double = 0

Dim amount As Double = 0
Dim customer_total As Double = 0

SQL = "SELECT invoice, product, cost, price, commission FROM billing_salesman_commission WHERE invoice = '" & reader2.GetString(0) & "';"
myCommand3.Connection = conn3
myCommand3.CommandText = SQL
reader3 = myCommand3.ExecuteReader
While reader3.Read
    'profit = sell price - cost price
     amount = reader3.GetString(3) - reader3.GetString(2)

     'commission amount = profit * (commission % / 100)
     amount = amount * (reader3.GetString(4) / 100)

     'update the customer total
     customer_total = customer_total + amount

     'insert excel data
     'MsgBox("insert excel")
End While
reader3.Close()

sub_total = sub_total + customer_total

从上面的查询创建一个循环,我已经在计算器上手动计算了所有数字。

invoice有2个唯一值,每个值总计如下:

  • 5.44
  • 9.41

应该等于14.85但是sub_total返回14.84

2 个答案:

答案 0 :(得分:2)

你试图减去字符串。对于代码字符串是一堆字母和符号,字符串中的数字被视为字母。

amount = reader3.GetString(3) - reader3.GetString(2)

您可以通过以下几种方式解决这个问题:

amount = (Convert.ToDecimal(reader3.GetString(3)))-(Convert.ToDecimal(reader3.GetString(2))


amount = CDec(reader3.GetString(3)) - CDec(reader3.GetString(2))

最佳方式,因为它会阻止异常:

<强>更新

更改这些:

Dim sub_total as Double = 0
Dim amount As Double = 0
Dim customer_total As Double = 0

为:

Dim sub_total, amount, customer_total As Decimal

那么这应该有效:

Dim costDec, sellDec, profit, commission as Decimal
If (Decimal.TryParse(reader3.GetString(3), costDec) AND Decimal.TryParse(reader3.GetString(2), sellDec) AND Decimal.TryParse(reader3.GetString(2), commission)) Then
    amount = costDec - sellDec
    profit = amount * (commission/100)
    customer_total = customer_total + profit
End If

只是对上述逻辑的评论,您的命名惯例很奇怪,因为它表明您只想计算利润佣金时计算客户的总成本。

答案 1 :(得分:1)

&#39;更改您的代码:

 Option strict on

 Dim sub_total as decimal= 0
 Dim amount As decimal= 0
 Dim customer_total As decimal= 0

   SQL = "SELECT invoice, product, cost, price, commission FROM billing_salesman_commission WHERE invoice = '" & reader2.GetString(0) & "';"

  myCommand3.Connection = conn3
  myCommand3.CommandText = SQL
  reader3 = myCommand3.ExecuteReader
     While reader3.Read

 'profit = sell price - cost price
 amount = cdec(reader3.GetString(3)) - cdec(reader3.GetString(2))

 'commission amount = profit * (commission % / 100)
 amount = amount * cdec(reader3.GetString(4) / 100)

 'update the customer total
 customer_total = cdec(customer_total) + cdec(amount)

 'insert excel data
 'MsgBox("insert excel")
 End While
 reader3.Close()

  sub_total = sub_total + customer_total