简体   繁体   中英

IsDouble check for string in Vb.net?

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?

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 .

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM