IsDouble check for string in Vb.net?

13,726

Solution 1

This is the wrong approach, you'll need to know up front what each column in the data table represents. Run this program to see what can go wrong:

Module Module1
    Sub Main()
        Dim value As Double
        If Double.TryParse("1e0", value) Then
            Console.WriteLine("Uh-oh")
        End If
        Console.ReadLine()
    End Sub
End Module

Solution 2

Dim val as Double
Double.TryParse("MyString", val)
Double.TryParse("1234.567", val)

First TryParse() will return false. Second TryParse() will return true and place 1234.567 into val.

Solution 3

Try Double.TryParse. This will return false if the number is not in a valid/recognized format, allowing you to do whatever you need to do in this scenario.

Solution 4

Just to expand on the (correct) answers already provided, here's a complete code example of how to use Double.TryParse:

Dim value As Double
If Double.TryParse(stringFromDataTable, value) Then
    ' text has been parsed as value, '
    ' so you can use value however you see fit '
Else
    ' text was not a valid double, so you can '
    ' notify the user or do whatever you want... '
    ' note that value will be zero in this case '
End If

Solution 5

May I ask why your storing doubles as strings and mixing them with non numeric string values? It seems to be like you would want to avoid doing that all costs.

Share:
13,726
James123
Author by

James123

Updated on June 14, 2022

Comments

  • James123
    James123 almost 2 years

    I will get data in DataTable. I am going to iterate data in foreach. I will have all types of data in Datatable. Now I need to find Double for each item (string) in DataTable. How to find IsDouble for string?

    Ex:

    I have "21342.2121" string. I need to covert this to Double. But sometimes the data will be "TextString". So I can't use Double.Parse().

    How to handle this?