Empty String to Double C#

后端 未结 5 1094
误落风尘
误落风尘 2021-01-05 17:56

At this moment i am trying to get a double value from textbox like this:

String.IsNullOrEmpty(textBox1.Text) ? 0.0 : Double.Parse(textBox1.Text)
相关标签:
5条回答
  • 2021-01-05 18:37

    If Double.TryParse is unable to parse the string, it returns false and sets the out parameter to 0.

    double d;
    if(double.TryParse(textBox1.Text, out d)
    {
      // valid number
    }
    else
    {
      // not a valid number and d = 0;
    }
    

    Or

    double d;
    double.TryParse(textBox1.Text, out d)
    // do something with d.  
    

    Also note that you can use the out parameter in additional logic within the same if statement:

    double d;
    if(double.TryParse(textBox1.Text, out d) && d > 500 && d < 1000)
    {
      // valid number and the number is between 501 and 9999
    }
    
    0 讨论(0)
  • 2021-01-05 18:46

    Did you try Double.TryParse(String, NumberStyles, IFormatProvider, Double%)?

    This could help to solve problems with various number formats.

    0 讨论(0)
  • 2021-01-05 18:46

    Why don't you just use Double.TryParse that doesn't throw exception?

    0 讨论(0)
  • 2021-01-05 18:57
    double result;
    Double.TryParse("",out result);
    

    If TryParse is true, the result will have a double value Further you can use if condition,

    result = Double.TryParse("",out result) ? result : 0.00
    
    0 讨论(0)
  • 2021-01-05 19:01
    double val;
    if(!double.TryParse(textBox.Text,out val))
        val = 0.0
    
    0 讨论(0)
提交回复
热议问题