简体   繁体   中英

Using double.Parse with a null value

Below is my statement:

double? My_Value = null;
   if (Request.Form["MyValue"] != null)
    My_Value = double.Parse(Request.Form["MyValue"].ToString());

When I try to submit my form with no value for 'MyValue' I get a run time error saying 'Input string was not in a correct format.'. When I try to use:

 My_Value = double.TryParse(Request.Form["MyValue"].ToString());

Visual Studio gives me a compile error that says 'No overload for method 'TryParse' takes 1 arguments'.

When I provide a value for 'My_Value', the form submits. How do I get the program to accept a null value? Thank you.

You need to declare a double variable to store the result and pass it to TryParse as an out argument, so it will be assigned if the parse succeeded:

double result;

var isValid = double.TryParse(Request.Form["MyValue"].ToString(), out result);

Also TryParse is different than Parse method, it doesn't return a numerical result, it returns a boolean result that indicates whether the parsing is succeeded or not.So you need to assign that result and check it's value to make sure parsing was successful.Or you could directly check the result without storing it in a variable.

double result;
double? My_Value = double.TryParse(Request.Form["MyValue"].ToString(), out result)
            ? (double?)result
            : null;

The signature for TryParse is bool TryParse(string str, out double result)

Use it like this:

double result;
var success = double.TryParse(Request.Form["MyValue"].ToString(), out result);

My_Value = success? result : 0d;

As "usr" mentioned in the comments, the next time you get an error like this, you should check the MSDN documentation first before coming here.

The problem with your first case isn't just about handling null s but rather about handling anything that cannot be parsed (since you are accepting a value from an untrustworthy source). Using TryParse is the way to go here.

However, the TryParse method accepts two arguments, the first the value to parse, the second a value to assign to if parsing succeeds (as an out) parameter.

For just such an occasion whereby you'd like a nullable result, a custom utility method can come in handy:

public static class NullableDouble
{
  public static double? TryParse(string input)
  {
    double result;
    var success = double.TryParse(input, out result);
    return success ? result as double? : null;
  }
}

Useable like so:

var myValue = NullableDouble.TryParse((Request.Form["MyValue"] ?? string.Empty).ToString());

Both solutions will result in 0;

string myString = null;
double result = Convert.ToDouble(myString);

OR

string myString = null;
double result = double.Parse(myString ?? "0");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM