.NET 支持两种类型的字符串格式。
我处于现有配置数据具有#,##0
样式格式的情况。一项新功能需要格式化为相同的输出,但此功能所需的 API 只接受 type 的格式{0:n2}
。
有谁知道在这两种数字类型表示之间进行转换的方法? DateTime
可以忽略。
编辑我了解到:
.NET 支持两种类型的字符串格式。
我处于现有配置数据具有#,##0
样式格式的情况。一项新功能需要格式化为相同的输出,但此功能所需的 API 只接受 type 的格式{0:n2}
。
有谁知道在这两种数字类型表示之间进行转换的方法? DateTime
可以忽略。
编辑我了解到:
不,你不能。
从您指向有关标准格式字符串的 MSDN 文章的链接,您会发现:
实际的负数模式、数字组大小、千位分隔符和小数分隔符由当前的 NumberFormatInfo 对象指定。
因此,标准格式说明符将根据程序运行的文化而有所不同。
由于您的自定义格式准确地指定了数字的外观,因此无论程序在何种文化下运行。它总是会看起来一样的。
程序运行的文化在编译时是未知的,它是一个运行时属性。
所以答案是:不,你不能自动映射,因为没有一对一的一致映射。
黑客警报!!!
正如Arjan 在他出色的回答中指出的那样,我想做的事情不可能在所有地区都以防弹的方式进行(感谢 Arjan)。
出于我的目的,我知道我只处理数字,而我关心的主要问题是具有相同的小数位数。所以这是我的黑客。
private static string ConvertCustomToStandardFormat(string customFormatString)
{
if (customFormatString == null || customFormatString.Trim().Length == 0)
return null;
// Percentages do not need decimal places
if (customFormatString.EndsWith("%"))
return "{0:P0}";
int decimalPlaces = 0;
int dpIndex = customFormatString.LastIndexOf('.');
if (dpIndex != -1)
{
for (int i = dpIndex; i < customFormatString.Length; i++)
{
if (customFormatString[i] == '#' || customFormatString[i] == '0')
decimalPlaces++;
}
}
// Use system formatting for numbers, but stipulate the number of decimal places
return "{0:n" + decimalPlaces + "}";
}
这用于将数字格式化为 2 个小数位
string s = string.Format("{0:N2}%", x);