This is a .NET Core 3.1 console app I've created to demonstrate an issue in a larger class library. I run it on a Windows 10 box build 18362
static void Main(string[] args)
{
string cur = "19,99 €";
CultureInfo ci = new CultureInfo("de-DE");
decimal num = decimal.Parse(cur, NumberStyles.Any, ci.NumberFormat);
}
Why does the line
decimal num = decimal.Parse(cur, NumberStyles.Any, ci.NumberFormat);
throw
System.FormatException: 'Input string was not in a correct format.'
EDIT
I've added the line
Debug.WriteLine(JsonConvert.SerializeObject(ci.NumberFormat, Formatting.Indented))
The output is
{
"CurrencyDecimalDigits": 2,
"CurrencyDecimalSeparator": ",",
"IsReadOnly": false,
"CurrencyGroupSizes": [
3
],
"NumberGroupSizes": [
3
],
"PercentGroupSizes": [
3
],
"CurrencyGroupSeparator": ".",
"CurrencySymbol": "€",
"NaNSymbol": "NaN",
"CurrencyNegativePattern": 8,
"NumberNegativePattern": 1,
"PercentPositivePattern": 0,
"PercentNegativePattern": 0,
"NegativeInfinitySymbol": "-∞",
"NegativeSign": "-",
"NumberDecimalDigits": 2,
"NumberDecimalSeparator": ",",
"NumberGroupSeparator": ".",
"CurrencyPositivePattern": 3,
"PositiveInfinitySymbol": "∞",
"PositiveSign": "+",
"PercentDecimalDigits": 2,
"PercentDecimalSeparator": ",",
"PercentGroupSeparator": ".",
"PercentSymbol": "%",
"PerMilleSymbol": "‰",
"NativeDigits": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
],
"DigitSubstitution": 1
}
EDIT 2 This code runs without exception when the German currency value is typed directly. However when the value is copied from the input stream that provides German currency values it throws the exception. I've tried looping through
foreach (char c in cur)
{
System.Diagnostics.Debug.WriteLine(Char.GetNumericValue(c));
}
with a breakpoint in the loop but c is always one of 19,99 €
How do I find what characters are causing
System.FormatException
to throw?
EDIT 3 The input stream that contains the German currency with a hidden character comes from the Microsoft Store,
StoreProduct.Price.FormattedPrice
The string "19,99 €" has an appended Unicode Character 160 Non-breaking space. By stripping this out as per https://stackoverflow.com/a/18018166 with
cur = Regex.Replace(cur, @"[^\u001F-\u007F]", string.Empty);
The problem goes away.