C#中Convert.ToDouble(variable)报Input string格式错误求解
Hey there! Let's break down why you're hitting this error when using Convert.ToDouble() in C#—even after adding .ToString(). Based on the context you shared, here are the most likely causes and actionable fixes:
Common Root Causes
- CSV Data Format Mismatches: Your CSV probably has values that don’t fit the default numeric format
Convert.ToDouble()expects. Examples include:- Numeric values with thousand separators (like
1,234.56) or currency symbols (like$123.45) - Using a comma as the decimal separator (common in European locales, e.g.,
1.234,56) instead of a period - Hidden whitespace, empty cells, or non-printable characters in the CSV fields
- Numeric values with thousand separators (like
- Invalid Source Value: Even after calling
.ToString(), the underlying value you’re trying to convert might beDBNull, an empty string, or a non-numeric string that can’t be parsed into a double.
Fixes to Try
Account for Culture-Specific Formats
If your CSV uses a non-default decimal separator (like commas), specify the correct culture during conversion. For example:using System.Globalization; // For locales using comma as decimal separator (e.g., French) double value = Convert.ToDouble(yourVariable.ToString(), CultureInfo.GetCultureInfo("fr-FR")); // Or use InvariantCulture to enforce period as decimal separator double value = Convert.ToDouble(yourVariable.ToString().Trim(), CultureInfo.InvariantCulture);Use
double.TryParse()for Safe Conversion & Debugging
Instead of relying onConvert.ToDouble()(which throws an error on failure), useTryParse()to gracefully handle invalid values and inspect what’s going wrong:using System.Globalization; if (double.TryParse(yourVariable.ToString().Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out double result)) { // Successfully converted—use 'result' here } else { // Log or print the problematic value to diagnose the issue Console.WriteLine($"Failed to convert: '{yourVariable}'"); }Clean Up Input Values First
Trim any leading/trailing whitespace from the CSV field before conversion—sometimes invisible spaces are the hidden culprit:string cleanedValue = yourVariable.ToString().Trim(); double value = Convert.ToDouble(cleanedValue, CultureInfo.InvariantCulture);
内容的提问来源于stack exchange,提问作者Arnas

