TryParse方法正在读取负值,并将其变为VB.Net代码中的正0

问题描述

我创建此代码是为了获得这些值的总和。

  Dim budget As Double
  If gv_DO_Tasks.Rows.Count() = 0 Then
        lblTotalTaskTotalBudget.Text = ""
        Return
    End If
    For Each i As GridViewRow In gv_DO_Tasks.Rows
        Dim amount As String = Replace(i.Cells(6).Text,"$"," ")
        Dim value As Double
        If Double.TryParse(amount,value) = True Then               
            budget = budget + value
        End If
        
    Next 

问题是我有一个负值作为金额之一,当我尝试执行TryParse方法将字符串形式的金额转换为双精度数时,该值变为0(作为正整数),而不是前一个价值是($ 26,652.25)或-$ 26,652.25这会使应该少的总金额混乱。总金额显示为$ 989,992.74,但应为$ 963,340.49。

我需要添加代码中或进行更改吗?

请帮助,谢谢。

解决方法

我怀疑用空格替换美元符号会给您留下这样的印象:

- 26,642.25

请注意负号和值之间的空格。如果您将美元符号替换为空字符串,那么我敢打赌代码会起作用:

Dim amount As String = Replace(i.Cells(6).Text,"$","")

我可能也很想写这样的实用程序/库方法:

<Extension()> 
Public Shared Iterator Function WhereDoubleParses(Of T)(items As IEnumerable(Of T),selector As Func(Of T,Double)) As IEnumerable(Of Double)
    For Each item As T in items
         Dim result As Double
         If (Double.TryParse(selector(item),result) Then
              Yield result
         End If
    Next
End Function

然后我将用来将原来的For循环缩减为以下形式:

budget = gv_DO_Tasks.Rows.
     WhereDoubleParses(Function(i) i.Cells(6).Text.Replace("$","")).
     Sum()