c# - 在 C#/.NET 中将字符串转换为整数

标签 c# asp.net

<分区>

我需要将字符串转换为整数。我的字符串可以是任何类型( float /整数/字符串/特殊字符)。

例如:

If my string is "2.3", I need to convert to = 2
If my string is "anyCharacter", I need to convert to = 0
If my string is "2", I need to convert to = 2

我尝试了以下方法:

string a = "1.25";int b = Convert.ToInt32(a);    

我得到了错误:

Input string was not in a correct format

如何转换?

最佳答案

使用 Double.TryParse() 并从中获取值后,使用 Convert.ToInt() 将其转换为 int:

double parsedNum;
if (Double.TryParse(YourString, out parsedNum) {
  newInt = Convert.ToInt32(num);
} 
else {
  newInt = 0;
}

关于c# - 在 C#/.NET 中将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15130138/

相关文章:

c# - 依赖注入(inject) - 处理多次注入(inject)的简洁方法

asp.net - 如何在vb.net中显示数据库中的数据

asp.net - 为什么将空格添加到我的 sql 表中的一行?

asp.net - "Update/Cancel"按钮未出现在 TemplateField 编辑按钮中

c# - 如何使用 DNX 和 ASP.NET 5 实现持续交付

c# - 从 OData 返回单个实体 - .Net

c# - 是否可以使用 C# 在 SQLite 中获取列名(标题)?

c# - 剪贴板调试

c# - 是否可以使用 WPF 在 c# 中更改 FormattedText 的 TextOptions?

c# - MVC 3 在错误的位置寻找图像