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 a DataRow
, the null coalescing operator will not evaluate to true when compared to DBNull
, thus the float parse will fail. You can compare for DBNull.Value
, or use float.TryParse()
.
From Original Code
aeVehicle.MSRP = float.Parse(drInvetory["MSRP"] == DBNull.Value ? "0" : drInvetory["MSRP"].ToString());
Personally, I would check for DBNull
and then cast to a float (or unbox to exact type, then cast). This saves a comparatively expensive string parse.
Better
aeVehicle.MSRP = drInvetory["MSRP"] == DBNull.Value ? default( float ) :
(float)drInvetory["MSRP"];
SQL-CLR type mapping: http://msdn.microsoft.com/en-us/library/bb386947.aspx
See also: Difference between decimal, float and double in .NET?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With