首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

string、object、double 轉 int 的最佳實踐心得

     編輯:關於.NET

許多開發者習慣使用 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
  • 安全處理 null/空字串/DBNull:統一回傳 0
  • 多型別重載:涵蓋 string、object、decimal、float、double、int、DBNull

將此工具類納入專案共用程式庫,可避免因資料格式不預期導致的轉型例外,提升系統健壯性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved