.净支持两个类型字符串的格式。

我在一个情况下,现有的配置数据 #,##0 风格的格式。一个新的功能需要的格式相同的输出,但API需要用于此功能只接受的格式类型 {0:n2}.

任何人都不会知道的一种手段之间的转换这两种表示数字类型? DateTime 可以忽略。

编辑 我学到的是:

有帮助吗?

解决方案

不,你不能。

从你的 链接到MSDN的文章有关的标准格式 弦,你会发现:

实际负数量的模式, 数目组的大小,千分离器, 和十进制分离器是指定的通过 当前NumberFormatInfo对象。

所以标准的格式指定者将根据其文化程序运行。

因为你定制的格式指定确切的数量如何去看看,无论文化在运行程序下。它总是会看起来是一样的。

文化的程序下运行是不知道在编制时间,这是一个运行时的财产。

所以答案是:不,你不能自动地图,因为没有一个一致的映射。

其他提示

黑客警报!!!

作为 阿尔扬指出的在他的极好的回答 我想做的事情不可能在一个防弹的时尚所有选择(感谢阿尔扬).

对我而言,我知道,我只处理数字和重要的事情对我而言是具有相同的小数位数。因此,这里是我的黑客。

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top