6

I output data from a process to a csv. I store intermediate results in a data class, which also has methods to output the data to a string so it can be written to a file.

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,
            );
        }
    }
}

Here i write to the file:

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

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

But the output file still has all the decimals:

Group  Value1   Value2  Value3
1   176983.222718191    278477.364780645    462811.208871335
2   11262339.27 16383.9680721473    118430.334721429

Does anyone know why it's ignoring the NumberFormatInfo?

When I check it in the debugger it looks just fine.

Thanks,

Gert-Jan

gjvdkamp
  • 9,929
  • 3
  • 38
  • 46
  • Can you post the code you use to write the file, any chance you are not using your `ValuesString` property? – Lazarus Jun 08 '11 at 11:47

1 Answers1

12

You have to use the N format specifier for Format to use the NumberFormatInfo. Try this

 return string.Format(nfi, "{0:N}\t{1:N}\t{2:N}",
            Value1,
            Value2,
            Value3,
        );
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
  • And then disallow the 1000 grouping. – H H Jun 08 '11 at 11:56
  • did this: NumberGroupSeparator="" or is there somehting faster? The real code has more fields. I switched to this approach from Value1.ToString("0") + "\t" + Value2.ToString("0") etc to make it faster. – gjvdkamp Jun 08 '11 at 11:59
  • 1
    You don't *have* to use `NumberFormatInfo`. You can just specify the number of decimal places in the format string, i.e. `"{0:0}\t{1:0}\t{2:0}"` – Tim Rogers Jun 08 '11 at 12:05
  • Ok that would clean it up, going with that. – gjvdkamp Jun 08 '11 at 12:14