将字符串转换为Int32错误

时间:2013-10-29 17:40:19

标签: vb.net casting

我正在尝试将字符串转换为int,由于某种原因,以下似乎可以正常工作。

Dim theInt As Int32 = CInt("55e5")
Console.WriteLine("String to Int32: " & theInt)

我无法理解为什么它正确转换并输出5500000

2 个答案:

答案 0 :(得分:1)

它将e5转换为科学记数法(认为这是正确的术语?),因此它将小数位数推过5次,因此5500000(5个额外的0)

答案 1 :(得分:0)

你期望55作为答案?旧的VB VAL()将返回该值。

我为我们的代码使用了自定义.Net Val()。主要处理美元符号,逗号,(),但可以扩展:

Public Function ValTest(ByVal value As String) As Double
    If String.IsNullOrEmpty(value) Then Return 0
    If IsNumeric(value) Then Return CDbl(value.Trim) ' IsNumeric and CDbl strip currency $ and comma, and support accounting negation e.g. ($23.23) = -23.23
    ' deal with case where leading/trailing non-numerics are present/expected
    Dim result As String = String.Empty
    Dim s As String = value.Trim
    If s.StartsWith("(") Then s.Replace("(", "-") ' leading ( = negative number from accounting - not supported by VB.Val()
    For Each c As Char In s
        If Char.IsNumber(c) OrElse "-.".Contains(c) Then
            result = (result + c)
        End If
    Next c
    If String.IsNullOrEmpty(result) Then
        Return 0
    Else
        Return CDbl(result)
    End If
End Function