///
/// 將數值格式化為千分位、指定小數位數的字串
///
public static string FormatMoney(double amount, int precision)
{
if (precision < 0) precision = 0;
if (precision > 10) precision = 10;
string format = "###,###,###,##0";
if (precision > 0)
format += "." + new string('0', precision);
return amount.ToString(format);
}
// 使用範例
Console.WriteLine(FormatMoney(2333, 2)); // 2,333.00
Console.WriteLine(FormatMoney(1234567.5, 3)); // 1,234,567.500
Console.WriteLine(FormatMoney(-9876.54, 2)); // -9,876.54
///
/// 將任意物件安全轉換為 double,失敗回傳 0.0
///
public static double ToDouble(object value)
{
// 1. Null/DBNull/空字串 → 0
if (value == null || value == DBNull.Value) return 0.0;
string str = value.ToString().Trim();
if (string.IsNullOrEmpty(str)) return 0.0;
// 2. 移除千分位逗號 (常見於字串金額 "1,234.56")
if (str.Contains(","))
str = str.Replace(",", "");
// 3. 嘗試解析
if (double.TryParse(str, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out double result))
return result;
return 0.0;
}
// 使用範例
object[] samples = { 123, 45.67, "1,234.56", "", null, DBNull.Value, "abc" };
foreach (var s in samples)
Console.WriteLine($"{s?.ToString() ?? "null",-12} → {ToDouble(s)}");
// 輸出:
// 123 → 123
// 45.67 → 45.67
// 1,234.56 → 1234.56
// → 0
// null → 0
// → 0
// abc → 0
public static double SumMoneyStrings(IEnumerable moneyStrings)
{
double sum = 0;
foreach (var s in moneyStrings)
sum += ToDouble(s);
return sum;
}
// 測試
var list = new[] { "1,000", "2,500.50", "3,000.25", "invalid", "" };
double total = SumMoneyStrings(list); // 6500.75
Console.WriteLine(FormatMoney(total, 2)); // 6,500.75
public static double ToDoubleAdvanced(object value)
{
if (value == null || value == DBNull.Value) return 0.0;
string str = value.ToString().Trim();
if (string.IsNullOrEmpty(str)) return 0.0;
// 移除常見貨幣符號
str = str.Replace(",", "").Replace("$", "").Replace("NT$", "").Replace("¥", "").Replace("€", "");
// 處理括號負數 (123) → -123
if (str.StartsWith("(") && str.EndsWith(")"))
str = "-" + str.Substring(1, str.Length - 2);
return double.TryParse(str, NumberStyles.Float | NumberStyles.AllowThousands | NumberStyles.AllowParentheses, CultureInfo.InvariantCulture, out double r) ? r : 0.0;
}
原文連結:https://www.bianceng.cn/Programming/csharp/201410/45582.htm