I want to parse a string to float. And when the string is null it will pass 0 (as a float valule).
I was doing the parse like this :
aeVehicle.MSRP = float.Parse((drInvetory["MSRP"] ?? "0").ToString());
Which gave errors :
ERROR MESSAGE : Input string was not in a correct format.
ERROR SOURCE : at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Single.Parse(String s, NumberStyles style, NumberFormatInfo info)
at System.Single.Parse(String s)
Please suggest the best way to handle this situation.
If
drInvetory["MSRP"]comes from aDataRow, the null coalescing operator will not evaluate to true when compared toDBNull, thus the float parse will fail. You can compare forDBNull.Value, or usefloat.TryParse().From Original Code
Personally, I would check for
DBNulland then cast to a float (or unbox to exact type, then cast). This saves a comparatively expensive string parse.Better
SQL-CLR type mapping: http://msdn.microsoft.com/en-us/library/bb386947.aspx
See also: Difference between decimal, float and double in .NET?