Search code examples
c#excelconsole.writeline

Printing out zeros after decimals into excel


I am trying to print out a double to excel. In my GUI the number prints out correctly.

But when I write the number to an excel file the number comes out with out the zeros after the decimal place. For examples the number 1.10 prints out correctly in my GUI, but in excel in prints out 1.1.

double foo = 1.10;
writeline(foo.ToString("F2"));

I have tried String.Format("{0:0.00}", foo.ToString("F2")); without resolving this issue. I am pretty sure the problem is when the number gets into excel, excel truncates all zeros after the decimal place. Is there a way to send excel a message to print out two places after the decimal?

I am working on someone elses code that opens and closes the excel file. They are using File.Create and StreamWriter to create and open the excel file


Solution

  • String.Format("{0:0.00}", foo.ToString("F2"));
    

    won't work, because you're trying to format something, that is converted to string already. Use a direct variable - your foo should return a numeric value and then you'd be able to use it like this (example):

    String.Format("{0:0.00}", foo.GetDouble("F2"));
    

    In other words:

    String.Format("{0:0.00}", "1.10");    //wrong
    String.Format("{0:0.00}", 1.10d);     //correct