[英]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"). 我有一个在某些区域性中包含数值的字符串(例如,字符串为“ $ 1000.00”,区域性为“ 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. "$ 1000.00"
en”文化中的"$ 1000.00"
=>“ ru”文化中的"1 000,00 $"
。
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: 但是,这不符合我希望的方式:double.TryParse“吃掉”有关货币符号,十进制数字等信息的所有信息。因此,如果我尝试使用这种方法,则:
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 $"
. 我只会得到1000
,而不是"1 000,00 $"
。
Is there an easy way to achieve this behavior using .NET? 是否有使用.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. Double.ToString(IFormatProvider)
方法使用默认的常规( "G"
)格式说明符,并且该说明符不返回当前NumberFormatInfo
对象的CurrencySymbol
属性。
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. 您可以仅使用"C"
(或货币)格式说明符作为您要查找的ToString
方法中的第一个参数。
result = numericResult.ToString("C", toFormat);
Here a demonstration
. 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. 顺便说一句, 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.