2013-10-29 89 views
0

我想将一个字符串转换为一个int,出于某种原因下面似乎工作。铸造字符串Int32错误

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

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

+0

这就是你想要的吗? – dbasnett

+0

是的,我甚至都没有意识到这个字符串是为科学记数法格式化的。 – GER

+0

所以我很清楚,我不想要550000.我期待捕捉有关输入错误的异常和警告用户。 – GER

回答

1

其转换是e5以科学记数法(认为这是适当的期限?),所以其推小数位的5倍以上,因此, 5500000(5多余的0)

+0

好听!谢谢 – GER

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