2011-06-08 23 views
6

我從一個進程輸出數據到csv。我將中間結果存儲在數據類中,該類還具有將數據輸出到字符串的方法,以便將其寫入文件。string.Format忽略NumberFormatInfo?

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?

當我在調試器中檢查它時,它看起來很好。

感謝,

格特 - 揚

+0

你可以發佈你用來編寫文件的代碼嗎,你有沒有機會使用'ValuesString'屬性? – Lazarus 2011-06-08 11:47:06

+0

好的我添加了那個代碼 – gjvdkamp 2011-06-08 11:48:47

回答

11

您必須使用N格式說明符Format使用NumberFormatInfo。試試這個

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

謝謝!那就是訣竅。 – gjvdkamp 2011-06-08 11:55:52

+0

然後禁止1000分組。 – 2011-06-08 11:56:38

+0

做到了這一點:NumberGroupSeparator =「」還是有更快?真正的代碼有更多的領域。我切換到這種方法從Value1.ToString(「0」)+「\ t」+ Value2.ToString(「0」)等,使其更快。 – gjvdkamp 2011-06-08 11:59:53