Currency Formatting - Windows Store Apps
In previous life of .Net, the way to format currency (any currency) for the current language would be to do something like this:
public string FormatCurrencyValue(string symbol, decimal val)
{
var format = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
//overwrite the currency symbol with the one I want to display
format.CurrencySymbol = symbol;
//pass the format to ToString();
return val.ToString("{0:C2}", format);
}
This returns the currency value without any decimal parts formatted for the given currency symbol, adjusted for the current culture - for example. £50.00
for en-GB
but 50,00£
for fr-FR
.
The same code that runs under Windows Store creates {50:C}
.
Looking at the (rather scary) WinRT documentation, we have a CurrencyFormatter class , but only after trying to hide the constructor using "£"
as a parameter, and getting ArgumentException
(the WinRT documentation is so special - it has practically no information about exceptions) that I realized that it you need an ISO currency symbol (honestly the name of the parameter currencyCode
, but even so).
Now - I can get one of them too, but CurrencyFormatter
has another problem that makes it unusable for currency formatting - you can only format tags double
, long
and ulong
- there is no decimal
overload - which can lead to some interesting value errors in some situations.
So how to dynamically format currencies in WinRT.net?
source to share
I found that you can still use old style strings with a class NumberFormatInfo
- it's just that it's inexplicable that it doesn't work when you use ToString
. If you use instead String.Format
, then it works.
So, we can rewrite the code in my question:
public string FormatCurrencyValue(string symbol, decimal val)
{
var format = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
//overwrite the currency symbol with the one I want to display
format.CurrencySymbol = symbol;
//pass the format to String.Format
return string.Format(format, "{0:C2}", val);
}
Which gives the desired result.
source to share