views:

132

answers:

5

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?

+5  A: 

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.

Will Vousden
Yes, Double.TryParse should help James123.
Ram
+3  A: 
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.

Anna Lear
+3  A: 

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
Dan Tao
+2  A: 

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.

T3hc13h
+2  A: 

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
Hans Passant