簡體   English   中英

在保留原始格式的同時,將包含數值的字符串轉換為具有不同區域性設置的相同字符串

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

我有一個在某些區域性中包含數值的字符串(例如,字符串為“ $ 1000.00”,區域性為“ en”)。 我想將此字符串轉換為其他區域性的字符串,同時保留盡可能多的有關原始格式的信息。 例如:

"$ 1000.00" en”文化中的"$ 1000.00" =>“ ru”文化中的"1 000,00 $"

我嘗試了最明顯的方法:

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 ,如果需要$作為結果,則可以Cloneru-RU文化,設置此CurrencySymbol屬性,然后在toFormat部分中使用克隆的文化。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM