Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Parse to Float, when input is Null

Tags:

c#

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.

like image 732
A Developer Avatar asked Sep 20 '12 07:09

A Developer


1 Answers

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?

like image 79
Tim M. Avatar answered Nov 13 '22 05:11

Tim M.