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

C# 金額字串格式化與物件轉 Double 通用工具方法

     編輯:關於C#

金額格式化:依精度產生千分位字串

/// 
/// 將數值格式化為千分位、指定小數位數的字串
/// 
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:處理 DBNull、逗號、空值

/// 
/// 將任意物件安全轉換為 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

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