It seems that many answers to this question involve replacing the culture's percentage symbol with the empty string, and then parsing the resulting string as a numeric value.
Perhaps I'm missing something, but there are still some unhandled cases here. Specifically, what happens if the PercentDecimalSeparator
is different to the NumberDecimalSeparator
for the current culture? What happens if the PercentGroupSeparator
is different to the NumberGroupSeparator
for the current culture? What happens if the PercentGroupSizes
are different to the NumberGroupSizes
?
Regardless of whether such a culture practically exists (if it doesn't, it may well come into existence in the future if the formatting for a culture is changed), I think that a better solution to the problem can be found if we consider these additional, special cases.
Here's a code snippet that shows a situation in which the other answers (based only on replacing the percent symbol) will fail, and a suggestion for how it could be done better properly:
// Modify a culture so that it has different decimal separators and group separators for numbers and percentages.
var customCulture = new CultureInfo("en-US")
{
NumberFormat = { PercentDecimalSeparator = "PDS", NumberDecimalSeparator = "NDS", PercentGroupSeparator = "PGS", NumberGroupSeparator = "NGS", PercentSymbol = "PS"}
};
// Set the current thread's culture to our custom culture
Thread.CurrentThread.CurrentCulture = customCulture;
// Create a percentage format string from a decimal value
var percentStringCustomCulture = 123.45m.ToString("p");
Console.WriteLine(percentStringCustomCulture); // renders "12PGS345PDS00 PS"
// Now just replace the percent symbol only, and try to parse as a numeric value (as suggested in the other answers)
var deceptiveNumericStringInCustomCulture = percentStringCustomCulture.Replace(customCulture.NumberFormat.PercentSymbol, string.Empty);
// THE FOLLOWING LINE THROWS A FORMATEXCEPTION
var decimalParsedFromDeceptiveNumericStringInCustomCulture = decimal.Parse(deceptiveNumericStringInCustomCulture);
// A better solution...replace the decimal separators and number group separators as well.
var betterNumericStringInCustomCulture = deceptiveNumericStringInCustomCulture.Replace(customCulture.NumberFormat.PercentDecimalSeparator, customCulture.NumberFormat.NumberDecimalSeparator);
// Here we mitigates issues potentially caused by group sizes by replacing the group separator by the empty string
betterNumericStringInCustomCulture = betterNumericStringInCustomCulture.Replace(customCulture.NumberFormat.PercentGroupSeparator, string.Empty);
// The following parse then yields the correct result
var decimalParsedFromBetterNumericStringInCustomCulture = decimal.Parse(betterNumericStringInCustomCulture)/100m;
Yes, the code is a bit longer, and perhaps I'm being pedantic (i.e. maybe such a culture will never actually exist). That said, it seems to me to be a more general solution. Hope it helps somebody :).