将包含数值的字符串转换为具有不同区域性设置的相同字符串,同时保留原始格式

本文关键字:字符串 设置 保留 格式 原始 区域性 包含数 转换 | 更新日期: 2023-09-27 18:06:04

我有一个字符串,它在某些区域性中包含一个数值(例如,字符串是"$ 1000.00",区域性是"en")。我希望将此字符串转换为其他区域性中的字符串,同时保留尽可能多的有关原始格式的信息。例如:

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

我已经尝试了最明显的方法:

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;
}

但是这并没有按照我想要的方式工作:double。TryParse"吃掉"有关货币符号、十进制数字等存在的所有信息。所以如果我尝试这样使用这个方法:

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

我只会得到1000,而不是"1 000,00 $"

是否有一个简单的方法来实现这种行为使用。net ?

将包含数值的字符串转换为具有不同区域性设置的相同字符串,同时保留原始格式

Double.ToString(IFormatProvider)方法使用通用("G")格式说明符作为默认,并且该说明符不返回当前NumberFormatInfo对象的CurrencySymbol属性。

你可以使用"C"(或货币)格式说明符作为你的ToString方法的第一个参数,这正是你正在寻找的。

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

Here a demonstration .

顺便说一下,ru-RU文化有作为CurrencySymbol,如果你想要$的结果,你可以Clone这个ru-RU文化,设置这个CurrencySymbol属性,并在你的toFormat部分使用那个克隆的文化。
var clone = (CultureInfo)toFormat.Clone();
clone.NumberFormat.CurrencySymbol = "$";
result = numericResult.ToString("C", clone);