简体   繁体   中英

Convert a string containing a numeric value to the same string with different culture settings while preserving the original format

I have a string that contains a numeric value in some culture (for example, the string is "$ 1000.00" and the culture is "en"). I want to convert this string to a string in the other culture while preserving as much information about the original format as possible. For example:

"$ 1000.00" in "en" culture => "1 000,00 $" in "ru" culture.

I've tried the most obvious approach:

private static bool TryConvertNumberString(IFormatProvider fromFormat, IFormatProvider toFormat, string number, out string result)
{
    double numericResult;
    if (!double.TryParse(number, NumberStyles.Any, fromFormat, out numericResult))
    {
        result = null;
        return false;
    }

    result = numericResult.ToString(toFormat);
    return true;
}

But this does not work the way I want it to: double.TryParse "eats" all information about the presence of currency sign, decimal digits, etc. So if I try to use this method like this:

string result;
TryConvertNumberString(new CultureInfo("en"), new CultureInfo("ru"), "$ 1000.00", out result);
Console.WriteLine(result);

I'll get just 1000 , not "1 000,00 $" .

Is there an easy way to achieve this behavior using .NET?

Double.ToString(IFormatProvider) method uses the general ( "G" ) format specifier be default and that specifier doesn't return CurrencySymbol property of the current NumberFormatInfo object.

You can just use The "C" (or currency) format specifier as a first parameter in your ToString method which is exactly what you are looking for.

result = numericResult.ToString("C", toFormat);

Here a demonstration .

By the way, ru-RU culture has as a CurrencySymbol , if you want $ in a result, you can Clone this ru-RU culture, set this CurrencySymbol property, and use that cloned culture in your toFormat part.

var clone = (CultureInfo)toFormat.Clone();
clone.NumberFormat.CurrencySymbol = "$";
result = numericResult.ToString("C", clone);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM