| 需求 | 程式碼範例 | 說明 |
|---|---|---|
| 僅截取 N 位,不四捨五入 | float f = 0.55555f; int i = (int)(f * 100); f = (float)(i * 1.0) / 100; | 乘以倍數取整後再除回 |
| 四捨五入保留 N 位 (Decimal) | decimal d = decimal.Round(decimal.Parse("0.55555"), 2); | Decimal 精度高,適合金融 |
| 四捨五入保留 N 位 (Math.Round) | Math.Round(0.55555, 2) | 預設銀行家算法 (ToEven) |
| 格式化輸出字串 | double db = 0.55555; string s = db.ToString("F2"); | F/N 格式指定小數位 |
| String.Format | String.Format("{0:N2}", 0.55555) | 含千分位分隔符 |
| 自訂格式字串 | double s = 0.55555; s.ToString("#0.00") | 0 代表必顯示,# 選擇性顯示 |
Math.Round 預設為 MidpointRounding.ToEven,需四捨五入請指定 MidpointRounding.AwayFromZero。decimal 避免浮點誤差。