[英]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.