Empty String to Double C#

南楼画角 提交于 2019-12-19 07:36:26

问题


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)

But there is a problem, i cant get how to parse empty textbox?

For example if to try this code with OleDb and Excel with empty textbox, we will get error

System.FormatException: Input string was not in a correct format.


回答1:


double val;
if(!double.TryParse(textBox.Text,out val))
    val = 0.0



回答2:


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

This could help to solve problems with various number formats.




回答3:


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
}



回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/12583371/empty-string-to-double-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!