[英]DateTime to string, formatting a line break into string while preserving culture
[英]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);
順便說一句, ru-RU
文化將₽
用作CurrencySymbol
,如果需要$
作為結果,則可以Clone
此ru-RU
文化,設置此CurrencySymbol
屬性,然后在toFormat
部分中使用該克隆的文化。
var clone = (CultureInfo)toFormat.Clone();
clone.NumberFormat.CurrencySymbol = "$";
result = numericResult.ToString("C", clone);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.