xxxxxxxxxx
/// <summary>
/// Ensures that the provided input string is formatted as currency based on the specified culture.
/// If the input is already in a valid currency format, it is returned unchanged. Otherwise, the string is parsed
/// as a decimal and formatted according to the specified culture's currency format.
/// </summary>
/// <param name="input">The input string representing a monetary value to be formatted.</param>
/// <param name="culture">The culture code used to format the currency. Defaults to "en" for English if not provided.</param>
/// <returns>
/// A string formatted as currency according to the specified culture. If the input cannot be parsed as a decimal,
/// the original input is returned unchanged.
/// </returns>
/// <example>
/// <code>
/// string formattedCurrency = EnsureCurrencyFormat("1234.56", "en-US");
/// Console.WriteLine(formattedCurrency); // Output: "$1,234.56"
/// </code>
/// </example>
internal static string EnsureCurrencyFormat(string input, string culture = "en")
{
if (!string.IsNullOrEmpty(culture))
culture = "en";
var cultureName = CultureInfo.GetCultures(CultureTypes.AllCultures).First(i => i.Name == culture);
// Check if the input is already in a valid currency format
if (IsCurrency(input))
{
return input; // Return as-is if it's already in currency format
}
// Try to parse the string as a decimal and format it as currency
if (!decimal.TryParse(input, out var amount)) return input; // Return original if it can't be parsed
var decimalLength = "C0";
if (!input.Contains("."))
return amount.ToString(decimalLength,
cultureName); // Format as currency with two decimals
var parts = input.Split('.');
// If there's a decimal point and something after it, return the length of the part after the decimal point
if (parts.Length > 1)
{
decimalLength = "C" + parts[1].Length;
}
return amount.ToString(decimalLength, cultureName); // Format as currency with two decimals
}
/// <summary>
/// Determines whether the given input string is in a valid currency format.
/// The method uses a regular expression to check if the input matches a pattern similar to "$100.00" or "€100.00".
/// </summary>
/// <param name="input">The string to check for currency format.</param>
/// <returns>
/// Returns <c>true</c> if the input string matches a valid currency format (e.g., "$100.00"),
/// otherwise returns <c>false</c>.
/// </returns>
/// <example>
/// <code>
/// bool isCurrency = IsCurrency("$100.00");
/// Console.WriteLine(isCurrency); // Output: True
/// </code>
/// </example>
private static bool IsCurrency(string input)
{
// Regular expression to check if string matches a currency format like "$100.00"
const string pattern = @"^[\p{Sc}]\d+(\.\d{1,2})?$";
return Regex.IsMatch(input, pattern);
}