0

I am trying to cast a string into an int and for some reason the following seems to work.

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

I am having trouble understanding why it converts correctly and outputs 5500000

4
  • Is that what you wanted? Commented Oct 29, 2013 at 17:56
  • Yes, I didn't even recognize that the string was formatted for Scientific notation. Commented Oct 29, 2013 at 18:04
  • So I am clear, I did not want 550000. I was expecting to catch exceptions and warning users about input errors. Commented Oct 30, 2013 at 11:48
  • Use Integer.TryParse to validate user input. Commented Oct 30, 2013 at 12:18

2 Answers 2

1

Its converting that e5 to scientific notation (think that's the proper term?), so its pushing the decimal place 5 times over, hence 5500000 (5 extra 0's)

Sign up to request clarification or add additional context in comments.

Comments

0

Where you expecting 55 as the answer? The old VB VAL() would return that.

I played with a custom .Net Val() for our code. In mostly deals with dollar signs, commas, (), but could be extended:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.