输入字符串的格式不正确_C#
Input string was not in a correct format_ C#
我有一个字段显示负数(示例-100.00)
我编写了以下代码将字符串转换为整数。但是,在调试时出现以下错误:输入字符串的格式不正确。
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
// convert string to int
int TValue = int.Parse(GetValue , NumberStyles.AllowLeadingSign| NumberStyles.AllowParentheses);
if (TValue > 0)
{
throw new Exception("In this method should return a negative value");
}
else
{
Console.WriteLine("good");
}
谁能帮我解决这个问题。
谢谢
你得到的错误是不言自明的。如果仔细观察,您正试图将浮点数(字符串类型)转换为整数。如果您尝试将 GetValue
转换为 double/float
,那么它将起作用。
使用 .TryParse()
而不是 Parse()
来检查转换是否有效。
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
if(double.TryParse(GetValue, out double total)
Console.WriteLine("good");
else
throw new Exception("In this method should return a negative value");
我有一个字段显示负数(示例-100.00)
我编写了以下代码将字符串转换为整数。但是,在调试时出现以下错误:输入字符串的格式不正确。
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
// convert string to int
int TValue = int.Parse(GetValue , NumberStyles.AllowLeadingSign| NumberStyles.AllowParentheses);
if (TValue > 0)
{
throw new Exception("In this method should return a negative value");
}
else
{
Console.WriteLine("good");
}
谁能帮我解决这个问题。 谢谢
你得到的错误是不言自明的。如果仔细观察,您正试图将浮点数(字符串类型)转换为整数。如果您尝试将 GetValue
转换为 double/float
,那么它将起作用。
使用 .TryParse()
而不是 Parse()
来检查转换是否有效。
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value");
if(double.TryParse(GetValue, out double total)
Console.WriteLine("good");
else
throw new Exception("In this method should return a negative value");