I have some customized string formats of double values. I need to convert these strings to double values at some point (Note that these strings may contain error messages other than numbers). So I first check if these strings are numbers, and if yes, then convert them to double. Isnumeric works for my first customized string format. But I found that is numeric cannot recognize percentage strings. I wonder why isnumeric understands () but cannot understand %. And what is the better way to convert “(100.00)” and “50%” to doubles other than Cdbl?
Private Format As String = "###,###,###,##0.00;(###,###,###,##0.00);0" 'negative values are in the format (number)
Private rateFormat as string="p"
Dim str1 as string=-100.0.Tostring(Format) 'str1=(100.0)
Dim str2 as string=0.5.Tostring(rateFormat) 'str2=50%
Dim value1,value2 as double
If isnumeric(str1)
value1=Cdbl(str1) 'True. value1=-100.0
else
value1=Double.MinValue
End If
If isnumeric(str2)
value2=cdbl(str2) 'False.value2=Double.Minvalue
else
value2=Double.MinValue
End If
First,
IsNumericandC<whatever>generally aren’t used because they can provide unexpected outputs. Typically you would useDouble.TryParseorConvert.ToDouble(or whatever type) because they reliably parses numbers as you would expect; you just have to make sure it’s in the right format.Also, those methods are more efficient because you can determine if a string is a number and parse it all in one go. Just note that
ParseandConvertthrow exceptions when the format is wrong.Now, as far as I know, there’s know built-in way convert from percent notation. I went ahead and wrote three methods (current culture, any culture, invariant culture) that tested fine with 0.5 and -0.5 on the four possible locations of the percent symbol.