Knob Parse to Float when entering Null

I want to parse a string for float. And when the string is zero, it will pass 0 (like a float valule).

I performed such a single:

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.

+5
source share
6 answers

If drInvetory["MSRP"]coming from DataRow, the zero coalescence operator will not be evaluated as true compared to DBNull, therefore, a floating point analysis will not be performed. You can compare for DBNull.Valueor use float.TryParse().

From source code

aeVehicle.MSRP = float.Parse(drInvetory["MSRP"] == DBNull.Value ? "0" : drInvetory["MSRP"].ToString());

Personally, I would check for DBNull, and then throw in a float (or unbox for the exact type, and then cast). This saves a relatively expensive parsing.

It's better

aeVehicle.MSRP = drInvetory["MSRP"] == DBNull.Value ? default( float ) : 
(float)drInvetory["MSRP"];

SQL-CLR: http://msdn.microsoft.com/en-us/library/bb386947.aspx
. : , .NET?

+8
float f = 0f;
string s = (drInvetory["MSRP"] ?? "0").ToString();
if (s != null) {
    f = float.Parse(s, ...
}
0

TryParse:

    float num = 0;
    float.TryParse(s, out num);
0

. .

0
float result = 0;
float.TryParse(drInvetory["MSRP"], out result);
aeVehicle.MSRP = result;

, , 0.

0

:

aeVehicle.MSRP = float.Parse("0" + drInvetory["MSRP"].ToString());

. Microsoft.VisualBasic.Val, .

0

All Articles