string.Format忽略NumberFormatInfo吗?

6

我将一个进程的数据输出到csv文件中。我将中间结果存储在一个数据类中,该类还具有将数据输出到字符串的方法,以便可以将其写入文件。

Class DataClass {

    // the actual data
    public double Value1 { get; set; } 
    public double Value2 { get; set; } 
    public double Value3 { get; set; } 

    // return headers for this dataclass (called once)
    public static string Headers { get { return "Value1\tValue2\tValue3"; } }

    // no decimals needed (keep filesize smaller, numbers are millions and up)
    static NumberFormatInfo nfi = new NumberFormatInfo() { NumberDecimalDigits = 0 }; 

    // this returns a string with the values for the dataclass (called for each row)
    public string ValuesString {
        get {
            // ** I would expect the numbers to have NO decimals because of nfi **
            return string.Format(nfi, "{0}\t{1}\t{2}",
                Value1,
                Value2,
                Value3,
            );
        }
    }
}

我在这里向文件写入:

// headers
swResultFile.WriteLine("Group\t" + GroupResult.Headers);

// values
foreach (var r in GroupResults) swResultFile.WriteLine(r.Key + "\t" + r.Value.ValuesString);

但输出文件仍然保留了所有的小数位:
Group  Value1   Value2  Value3
1   176983.222718191    278477.364780645    462811.208871335
2   11262339.27 16383.9680721473    118430.334721429

有人知道为什么它忽略了NumberFormatInfo吗?

当我在调试器中检查时,它看起来很好。

谢谢,

Gert-Jan


你能否发布你用于编写文件的代码?有没有可能你没有使用你的 ValuesString 属性? - Lazarus
1个回答

12

您需要使用N格式说明符来让Format使用NumberFormatInfo。请尝试以下代码:

 return string.Format(nfi, "{0:N}\t{1:N}\t{2:N}",
            Value1,
            Value2,
            Value3,
        );

然后禁止1000分组。 - H H
你做了这个:NumberGroupSeparator="" 或者有更快的方法吗?实际代码有更多字段。我从Value1.ToString("0") + "\t" + Value2.ToString("0")等切换到这种方法以使其更快。 - gjvdkamp
1
你不一定需要使用 NumberFormatInfo。你可以在格式字符串中指定小数位数,例如 "{0:0}\t{1:0}\t{2:0}" - Tim Rogers
好的,那样会使它更清晰,我们采用那个方案。 - gjvdkamp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接