Home > Software design >  vb.net How to convert the string "one" to an integer 1
vb.net How to convert the string "one" to an integer 1

Time:09-16

I think my question is fairly simple but i just cant seem to get it to work. I have to change my variable from the string "One" to the integer 1 looks like this

BeginningValue = Int32.Parse(numbers(index))

I have also tried

BeginningValue = Convert.ToInt32(numbers(index))

but that doesnt seem to work either. Both of these lines just give me the error "System.FormatException: Input string was not in a correct format."

CodePudding user response:

There is no built-in library to convert words to numbers.

If you have a finite list of words that you want to convert, then you can store them in a dictionary and get the value by its key. E.g.:

Dim wordsToNumber = New Dictionary(Of String, Integer)() From {
    { "One", 1 },
    { "Two", 2 },
    { "Three", 3 }
}

Dim input = "One"
If (wordsToNumber.ContainsKey(input)) Then
    Dim beginningValue = wordsToNumber(input)
    Console.WriteLine(beginningValue)
End If

However, if you want to allow for any combination (e.g. One Thousand Twenty Five) then it is best to go with an existing algorithm. Here is a C# example that can be put through a converter: enter image description here

  • Related