To pass null values to float data type to add it i

2019-08-20 04:38发布

问题:

I am trying to pass the null value to float data type as follow,

float? period_final_value = null; 

and getting the value in period_final_value from the parsing xml string as follows

var action = xmlAttributeCollection_for_period["value"];
xmlActionsone[j] = action.Value;
period_final_value = float.Parse(action.Value); 

and then adding this obtained value to list as follows

serie_line.data.Add(period_final_value);

Defined my list as follows

var serie_line = new { name = series_name, data = new List<float?>() };

Now, My issue is when I am trying to pass value,it shold get add to the list, and moment when no value is recognized then it should add null has the value in the place of empty value in list but I don't know I am not able to get it work properly...my web service crashes moment it counters any blank value...any help will be greatly appreciated...

plz note...the var serie_line..I am going to serialize it into JSON format so that I can use those values to plot chart.

回答1:

It sounds like you might be looking for TryParse instead of Parse.

When you call period_final_value = float.Parse(action.Value);, Parse will either parse the string into a float or throw an exception. It will never return null.

To get the behavior you want, try something like this:

float temp_value = 0;
float? period_final_value = null;
if (float.TryParse(action.Value, out temp_value)) {
    period_final_value = temp_value;
}

serie_line.data.Add(period_final_value);

If action.Value is a string representation of a number, then period_final_value will be that number. Otherwise, it will be null. You can then add it to your list of float? values.



回答2:

At this line

float? period_final_value = float.Parse(action.Value); 

you are loosing the nullable float. When it fails to parse (there is no value or the value is not a valid float), it throws instead of returning null. period_final_value will never have null as a value.

See gleng's answer to be able to set null to period_final_value.