Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何在“之间转换”##0“;及;{0:n2}";样式格式字符串表示?_.net_Formatting_String Formatting - Fatal编程技术网

.net 如何在“之间转换”##0“;及;{0:n2}";样式格式字符串表示?

.net 如何在“之间转换”##0“;及;{0:n2}";样式格式字符串表示?,.net,formatting,string-formatting,.net,Formatting,String Formatting,.NET支持两种类型的字符串格式 我所处的情况是,现有配置数据具有,#0样式格式。新功能要求格式化为相同的输出,但此功能所需的API只接受{0:n2}类型的格式化 有人知道在这两种表示形式之间转换数字类型的方法吗日期时间可以忽略 编辑我了解到: {0:n2}样式称为 #,##0样式称为 不,你不能 从字符串中,您将发现: 实际的负数模式, 数字组大小,千位分隔符, 和十进制分隔符由指定 当前NumberFormatInfo对象 因此,标准格式说明符将根据程序运行的区域性而有所不同 由于您的自定

.NET支持两种类型的字符串格式

我所处的情况是,现有配置数据具有
,#0
样式格式。新功能要求格式化为相同的输出,但此功能所需的API只接受
{0:n2}
类型的格式化

有人知道在这两种表示形式之间转换数字类型的方法吗<代码>日期时间可以忽略

编辑我了解到:

  • {0:n2}
    样式称为

  • #,##0
    样式称为

  • 不,你不能

    从字符串中,您将发现:

    实际的负数模式, 数字组大小,千位分隔符, 和十进制分隔符由指定 当前NumberFormatInfo对象

    因此,标准格式说明符将根据程序运行的区域性而有所不同

    由于您的自定义格式精确地指定了数字的外观,因此无论程序运行在何种区域性下。一切看起来都一样

    程序运行的区域性在编译时是未知的,它是一个运行时属性


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

    黑客警报

    因为我想做的事情不可能在所有地区都是防弹的(谢谢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 + "}";
    }
    
    私有静态字符串转换器CustomToStandardFormat(字符串customFormatString)
    {
    if(customFormatString==null | | customFormatString.Trim().Length==0)
    返回null;
    //百分比不需要小数位
    if(customFormatString.EndsWith(“%”)
    返回“{0:P0}”;
    整数小数位数=0;
    int dpIndex=customFormatString.LastIndexOf('.');
    如果(dpIndex!=-1)
    {
    for(inti=dpIndex;i
    用于将数字格式化为2位小数

    string s = string.Format("{0:N2}%", x);
    

    @阿扬,当。我真的没有在我的区域之外思考,因为这是一个内部应用程序,但感谢您的解释。这些不同格式的目的现在对我来说已经很清楚了。回答得很好。