You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

转换为Decimal触发System.FormatException,求商品价格计算功能修复方案

Fixing System.FormatException in Your Product Price Calculation Feature

Hey there, let's work through this System.FormatException you're hitting. This error almost always pops up when trying to convert a string to a numeric type (like decimal or int) and the string doesn't match a valid number format. Let's break down the most common causes and how to fix them step by step.

Common Causes & Solutions

1. Your Label Contains Non-Numeric Characters

If your Label's text includes things like currency symbols ($, ¥), commas, spaces, or text (e.g., "元", "USD"), direct conversion will fail. For example, trying to parse "$29.99" or "150 元" will throw the exception.

Fix: Clean the string first to remove non-numeric/non-decimal characters, then use safe parsing:

private void ProductLabel_Click(object sender, EventArgs e)
{
    Label clickedLabel = sender as Label;
    if (clickedLabel == null) return;

    string rawPrice = clickedLabel.Text.Trim();
    // Remove all characters except numbers and decimal points
    string cleanedPrice = System.Text.RegularExpressions.Regex.Replace(rawPrice, @"[^0-9.]", "");

    decimal productPrice;
    if (decimal.TryParse(cleanedPrice, out productPrice))
    {
        // Calculate total (adjust this logic to fit your total tracking method)
        decimal totalPrice = 0; // Replace with your existing total variable
        totalPrice += productPrice;
        // Format the total to a user-friendly string (e.g., with currency)
        TotalTextBox.Text = totalPrice.ToString("C2");
    }
    else
    {
        // Handle invalid price case gracefully
        TotalTextBox.Text = "Invalid price format";
    }
}

2. The Label Is Empty or Contains Only Whitespace

If the Label's text is blank or just spaces, parsing will fail immediately. Always validate the input before trying to convert it.

Fix: Add a check for empty/whitespace strings upfront:

private void ProductLabel_Click(object sender, EventArgs e)
{
    Label clickedLabel = sender as Label;
    if (clickedLabel == null) return;

    string rawPrice = clickedLabel.Text.Trim();
    if (string.IsNullOrWhiteSpace(rawPrice))
    {
        TotalTextBox.Text = "Please select a valid product";
        return;
    }

    // Rest of your cleaning/parsing logic here
}

3. Culture/Format Mismatches

If your app uses a culture where commas are decimal separators (e.g., French, German) but your price strings use periods (or vice versa), parsing will fail.

Fix: Use CultureInfo.InvariantCulture to standardize parsing:

if (decimal.TryParse(cleanedPrice, System.Globalization.NumberStyles.Number, 
    System.Globalization.CultureInfo.InvariantCulture, out productPrice))
{
    // Your calculation logic
}

4. Using Unsafe Parsing Methods

If your original code used decimal.Parse() or Convert.ToDecimal() instead of TryParse(), these methods throw exceptions instead of handling invalid input gracefully.

Bad Code (Causes Exception):

// Risky - throws FormatException if string is invalid
decimal price = decimal.Parse(clickedLabel.Text);

Good Code (Safe):

// Safe - returns false instead of throwing an exception
if (decimal.TryParse(cleanedPrice, out decimal price))
{
    // Use the price
}

Debugging Tip

To pinpoint exactly what's causing the error, add a debug line to check the Label's actual content when the click event fires:

Debug.WriteLine($"Label Text: '{clickedLabel.Text}'");

This will show you the exact string that's failing to parse, so you can adjust your cleaning logic accordingly.


内容的提问来源于stack exchange,提问作者Izzah Nrl Zulkipli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:10:37