标签:text try out .com res console result 小数点 ble
在C# 中想要将String类型转换成int时有以下几种方法:
int.TryParse;
Convert.Toint32;
(int)string;
但是,
使用Convert.ToInt32(string) 会出现输入字符串格式错误问题。
使用Int.TryParse(string)也会转换失败,不会错误,会输出默认的0
解决方案是使用Decimal或者Double去转换
(1)使用Decimal.Parse
string a = "23.00";
decimal c = decimal.Parse(a);Console.WriteLine("result:{0}", (int)c);string a = "23.00";
Double c = Double.Parse(a);Console.WriteLine("result:{0}", (int)c);注:当使用(int)string强行转换的时候你会发现如果带有小数点系统会被自动忽略。
如果使用Convert.ToInt32转换时系统会四舍五入。
附:如何实现一个类型的扩展类。
public static class ObjectExtension
{ public static int ToInt(this object obj) { int result = default(int); if (obj != null && obj != DBNull.Value) { int.TryParse(obj.ToString(), out result); } return result; }}
标签:text try out .com res console result 小数点 ble
原文地址:http://www.cnblogs.com/weimingxin/p/7301071.html