許多開發者習慣使用 Convert.ToInt32 強制轉型,但發現當字串為小數格式或科學計數法時會拋出例外。解決方案:先嘗試解析為 decimal,再轉為 int。
public static int Do(string value) {
if (string.IsNullOrEmpty(value)) return 0;
decimal result = 0;
decimal.TryParse(value, out result);
return System.Convert.ToInt32(result);
}
namespace CS.Convert {
public class ToInt {
public static int Do(string value) {
if (string.IsNullOrEmpty(value)) return 0;
decimal result = 0;
decimal.TryParse(value, out result);
return System.Convert.ToInt32(result);
}
public static int Do(decimal value) {
return System.Convert.ToInt32(value);
}
public static int Do(float value) {
return System.Convert.ToInt32(value);
}
public static int Do(double value) {
return System.Convert.ToInt32(value);
}
public static int Do(int value) {
return value;
}
public static int Do(object value) {
if (null == value || string.IsNullOrEmpty(value.ToString())) return 0;
decimal result = 0;
decimal.TryParse(value.ToString(), out result);
return System.Convert.ToInt32(result);
}
public static int Do(DBNull value) {
return 0;
}
}
}
"123.45" → 123"1.23E2" → 123將此工具類納入專案共用程式庫,可避免因資料格式不預期導致的轉型例外,提升系統健壯性。