| 特性 | float (System.Single) | double (System.Double) | decimal (System.Decimal) |
|---|---|---|---|
| 位元數 | 32-bit | 64-bit | 128-bit |
| 有效位數 | ~7 位 | ~15-17 位 | 28-29 位 |
| 範圍 | ±1.5e-45 ~ ±3.4e38 | ±5.0e-324 ~ ±1.7e308 | ±1.0e-28 ~ ±7.9e28 |
| IEEE 754 | Binary32 | Binary64 | 否 (十進制浮點) |
| 預設值 | 0.0f | 0.0 | 0.0m |
| 字面常值 | 1.5f | 1.5 | 1.5m |
| 適用場景 | 3D 圖形、GPU、大量陣列 | 科學計算、一般用途 | 財務、金融、精確十進制 |
// float/double 二進制無法精確表示 0.1
float f = 0.1f; // 0.10000000149011612
double d = 0.1; // 0.10000000000000001
decimal m = 0.1m; // 0.1 精確
// 錯誤比較
bool bad = (0.1 + 0.2) == 0.3; // false
// 正確:容差比較
bool AlmostEqual(double a, double b, double eps = 1e-10)
=> Math.Abs(a - b) < eps;
// 相對誤差比較 (適合大數值)
bool RelativeEqual(double a, double b, double relEps = 1e-12) {
double diff = Math.Abs(a - b);
double max = Math.Max(Math.Abs(a), Math.Abs(b));
return diff <= max * relEps;
}
double.NaN // 非數值 (0/0, Sqrt(-1))
double.PositiveInfinity // 1.0/0.0
double.NegativeInfinity // -1.0/0.0
// 檢查方法
double.IsNaN(x)
double.IsInfinity(x)
double.IsFinite(x) // .NET 6+
// NaN 特性:NaN != NaN 為 true
// 唯一透過 IsNaN 或 x != x 檢測
// 隱含:float → double (精度提升)
double d = 1.5f;
// 顯性:double → float (可能精度遺失/溢位)
float f = (float)1.5;
// decimal 無隱含轉換 (精度語意不同)
decimal m = (decimal)1.5; // 從 double 需顯性
double d2 = (double)1.5m; // 從 decimal 需顯性
// 整數轉換
float f2 = 1000000; // 精確 (24-bit 尾數)
float f3 = 16777217; // 變 16777216 (精度遺失)
float[] 記憶體 1/2 double[],1/4 decimal[],Cache 友善Vector<float>/Vector<double> 硬體向量化,decimal 無 SIMDdouble 平衡精度/效能;圖形/GPU:float
需要精確十進制表示 (金額、稅率、利率)?
├─ 是 → decimal (唯一正確選擇)
└─ 否 → 需要極大範圍 (天文、物理常數)?
├─ 是 → double (範圍至 1e308)
└─ 否 → 大量陣列/GPU/記憶體敏感?
├─ 是 → float (7 位有效數字通常足夠)
└─ 否 → double (預設最佳平衡)

