2011-06-08 20 views
6

I datos de salida de un proceso a un csv. Guardo los resultados intermedios en una clase de datos, que también tiene métodos para generar los datos en una cadena para que pueda escribirse en un archivo.string.Format ignora 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, 
      ); 
     } 
    } 
} 

Aquí i escribir en el fichero:

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

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

Sin embargo, el archivo de salida todavía tiene todos los decimales:

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

¿alguien sabe por qué está haciendo caso omiso de la NumberFormatInfo?

Cuando lo compruebo en el depurador se ve muy bien.

Gracias,

Gert-Jan

+0

¿Puede publicar el código que utiliza para escribir el archivo, cualquier posibilidad de que no esté utilizando su propiedad 'ValuesString'? – Lazarus

+0

bien, agregué ese código – gjvdkamp

Respuesta

11

Tienes que usar el especificador de formato para NFormat utilizar el NumberFormatInfo. Pruebe esto

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

¡Gracias! Eso hizo el truco. – gjvdkamp

+0

Y luego no permitir la agrupación de 1000. –

+0

hizo esto: NumberGroupSeparator = "" o ¿hay algo más rápido? El código real tiene más campos. Cambié a este enfoque de Value1.ToString ("0") + "\ t" + Value2.ToString ("0"), etc. para hacerlo más rápido. – gjvdkamp