空字符串加倍C#
此刻我正试图从文本框中获取双倍值,如下所示:
String.IsNullOrEmpty(textBox1.Text) ? 0.0 : Double.Parse(textBox1.Text)
但是有一个问题,我无法解决如何解析空文本框?
例如,如果使用带有空文本框的OleDb和Excel尝试此代码,我们将收到错误
System.FormatException:输入字符串的格式不正确。
double val; if(!double.TryParse(textBox.Text,out val)) val = 0.0
你尝试过Double.TryParse(String, NumberStyles, IFormatProvider, Double%)
吗?
这可以帮助解决各种数字格式的问题。
如果Double.TryParse
无法解析字符串,则返回false并将out参数设置为0。
double d; if(double.TryParse(textBox1.Text, out d) { // valid number } else { // not a valid number and d = 0; }
要么
double d; double.TryParse(textBox1.Text, out d) // do something with d.
另请注意,您可以在同一if语句中的其他逻辑中使用out参数:
double d; if(double.TryParse(textBox1.Text, out d) && d > 500 && d < 1000) { // valid number and the number is between 501 and 9999 }
double result; Double.TryParse("",out result);
如果TryParse为true,则结果将具有double值。如果条件,则可以使用
result = Double.TryParse("",out result) ? result : 0.00
你为什么不使用不抛出exception的Double.TryParse?