Bulding on Robert Atkins' answer, it is possible to do the same thing on .NET. To test this code, create a Console App project and replace Program.cs with this:
using System;
using System.Globalization;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
decimal amount = 100.123M;
Console.WriteLine(GetNumberOfDecimales("USD", 2)); // 2
Console.WriteLine(GetNumberOfDecimales("EUR", 2)); // 2
Console.WriteLine(GetNumberOfDecimales("JPY", 2)); // 0
Console.WriteLine(GetNumberOfDecimales("BHD", 2)); // 3
Console.WriteLine(GetNumberOfDecimales("___", 2)); // 2
Console.WriteLine(LocalizeAmount(amount, "USD")); // 100.12
Console.WriteLine(LocalizeAmount(amount, "EUR")); // 100.12
Console.WriteLine(LocalizeAmount(amount, "JPY")); // 100
Console.WriteLine(LocalizeAmount(amount, "BHD")); // 100.123
Console.WriteLine(LocalizeAmount(amount, "___")); // 100.12
}
/// <summary>
///
/// Returns an amount with the correct number of decimals for the given currency.
/// The amount is rounded.
///
/// Ex.:
/// 100.555 JPY => 101
/// 100.555 USD => 100.56
///
/// </summary>
static public string LocalizeAmount(decimal amount, string currencyCode)
{
var formatString = String.Concat("{0:F", GetNumberOfDecimales(currencyCode, 2), "}"); // {0:F2} for example
return String.Format(formatString, amount);
}
/// <summary>
///
/// Returns the number of decimal places for a currency.
///
/// Ex.:
/// JPY => 0
/// USD => 2
///
/// </summary>
static public int GetNumberOfDecimales(string currencyCode, int defaultValue = 2)
{
var cultureInfo = GetFirstCultureInfoByCurrencySymbol(currencyCode);
return cultureInfo?.NumberFormat?.CurrencyDecimalDigits ?? defaultValue;
}
static private CultureInfo GetFirstCultureInfoByCurrencySymbol(string currencySymbol)
{
if (string.IsNullOrWhiteSpace(currencySymbol))
throw new ArgumentNullException("A valid currency must be provided.");
return CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.FirstOrDefault(x => new RegionInfo(x.LCID).ISOCurrencySymbol == currencySymbol);
}
}
}