Decimal.TryParse failed in da-DK culture.

D

dehranph

I have this code that always return zero whenever i passed 1,000,00 in
a da-DK culture or en-US culture. It works with amount less that 1000
like 99,99. but always returns 0 when greater than or equal to 1000.
Decimal separator is ",". I suspect its because the decimal and
thousand separator are the same.

Thread.CurrentThread.CurrentCulture = new
CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol = "";
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
= ",";
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyGroupSeparator
= ",";
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalDigits
= 2;

Thread.CurrentThread.CurrentUICulture = new
CultureInfo(Thread.CurrentThread.CurrentUICulture.Name);
Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencySymbol =
"";
Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyDecimalSeparator
= ",";
Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyGroupSeparator
= ",";
Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyDecimalDigits
= 2;


/// <summary>
/// Try parse string input into decimal value.
/// </summary>
/// <param name="inputValue">The input value.</param>
/// <param name="valueWhenNull">The value when null or failed to
parse.</param>
/// <returns></returns>
public static decimal TryParseDecimal(string inputValue, string
valueWhenNull) {
inputValue = inputValue ?? valueWhenNull;

decimal returnedValue = 0;
decimal.TryParse(inputValue, NumberStyles.Currency,
NumberFormatInfo.CurrentInfo, out returnedValue);

return returnedValue;
}
 
J

Jon Skeet [C# MVP]

I have this code that always return zero whenever i passed 1,000,00 in
a da-DK culture or en-US culture. It works with amount less that 1000
like 99,99. but always returns 0 when greater than or equal to 1000.
Decimal separator is ",". I suspect its because the decimal and
thousand separator are the same.

Are you *specifically* setting the decimal and group separator to the
same thing in your real code? A simple test program I wrote showed that
in da-DK, CurrencyDecimalSeparator is "," and CurrencyGroupSeparator is
".".

If you're setting them to the same thing programmatically, that's a
really bad idea, and will indeed have the kind of effect you're seeing.
 
Top