0

I'm using this code for exporting from my SQL Server to a .txt file. When I use a column which is typed as float, I want to get specific view.

So this let's say that my column value is '1', I want to get a result of 1.000, or if it is 1.1, I want the result to be 1.100. Also if I have 0.5, the desired result is 0.500.

Here is my code:

SqlDataReader read = cmd.ExecuteReader();

using (StreamWriter sw = new StreamWriter(@"C:\xxx.txt"))
{
    while (read.Read())
    {
        sw.Write(read["Quantity"].ToString());
    }
}

I have already tried to convert to demical but I get same result. Example if my column is 1, I get result 1.

I have also use padright but it doesn't take my separator.

  sw.Write(read["Quantity"].ToString().PadRight(4,'0'));
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dim
  • 97
  • 2
  • 9
  • 1
    [start here](https://msdn.microsoft.com/en-us/library/ek5h49e6(v=vs.110).aspx). Either specify a format string in the call to `ToString()`, or set the `FormatProvider` property of the `StreamWriter`. – Cee McSharpface Apr 30 '17 at 10:27
  • I tried this but i get same result Double d = Double.Parse(read["Quantity"].ToString()); sw.Write(d); – Dim Apr 30 '17 at 10:33
  • This might help you http://stackoverflow.com/questions/6356351/formatting-a-float-to-2-decimal-places – iaresti Apr 30 '17 at 10:35
  • Is different method for streamwriter? – Dim Apr 30 '17 at 10:39
  • Please give me an example – Dim Apr 30 '17 at 10:44

1 Answers1

1

try this:

String.Format("{0:0.000}", 0.5);

just put your number at 0.5

SqlDataReader read = cmd.ExecuteReader();
using (StreamWriter sw = new StreamWriter(@"C:\xxx.txt"))
{
    while (read.Read())
    {
        sw.Write(String.Format("{0:0.000}", double.Parse(read["Quantity"].ToString())));
    }
}
Shahrooz Ansari
  • 2,637
  • 1
  • 13
  • 21