C# int.Parse转换负数字符串报Input string was not in a correct format错误如何解决
问题原因
- 待解析的字符串取值为
-100.00,包含小数点和小数位,而int是整数类型,本身不支持存储小数,int.Parse方法也不支持解析带小数点的字符串,即使添加对应的NumberStyles配置也会触发格式错误。 - 当前传入的
NumberStyles组合仅允许前导负号、括号表示负数,没有兼容小数点的配置,即使使用支持小数的类型解析,当前配置也会报错。 - 额外排查项:通过页面属性拿到的字符串可能存在前后空白字符,未处理的情况下也会触发格式错误。
解决方案
根据业务需求选择对应方案:
方案1:仅需整数结果,可丢弃小数部分
先将字符串解析为支持小数的decimal类型,再转换为int:
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value")?.Trim(); // 先解析为decimal兼容小数位 decimal tempVal = decimal.Parse(GetValue, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint); // 转int:(int)会直接截断小数,如需四舍五入可改用Convert.ToInt32(tempVal) int TValue = (int)tempVal; if (TValue > 0) { throw new Exception("In this method should return a negative value"); } else { Console.WriteLine("good"); }
如果你的场景中负数会用括号形式表示(如(100.00)代表-100.00),可以在NumberStyles中追加AllowParentheses参数。
方案2:需要保留小数精度
直接将存储变量的类型替换为decimal即可:
var GetValue = driver.FindElement(By.Id("txtTotal")).GetAttribute("value")?.Trim(); decimal TValue = decimal.Parse(GetValue, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint); if (TValue > 0) { throw new Exception("In this method should return a negative value"); } else { Console.WriteLine("good"); }
内容的提问来源于stack exchange,提问作者Tester
相关产品推荐
相关产品推荐

