NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "$";
var result1 = decimal.Parse("$123456", NumberStyles.Any, nfi).Dump(); // this works well
var result2 = Convert.ChangeType("$123456", typeof(decimal), nfi); // this doesn't work
I need Convert.ChangeType() to accept currency, is it possible? Tried setting NumberFormatInfo but looks like it ignores currency values.
Convert
is a static class and also ChangeType()
is a static method, so you can not override them.
Even if this is not exactly what you have asked for, however, you may create your own class change the way you want it to work for decimal (and any others) and use Convert.ChangeType()
as default for other types:
public static class MyConvert
{
public static object? ChangeType(object? value, Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(decimal))
return decimal.Parse(value.ToString(), NumberStyles.Any, provider);
else
return Convert.ChangeType(value, conversionType, provider);
}
}
Now the following code would work as you expect:
var result2 = MyConvert.ChangeType("$123456", typeof(decimal), nfi);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With