I need to write several doubles in text file with dot separator. I know, that this code is the solution:
StreamWriter f = new StreamWriter(file, Encoding.ASCII, 128, false);
double a = 1.057887;
f.Write(a.ToString("G5", CultureInfo.InvariantCulture));
but I have too many numbers to write, so I tried method from this answer:
f.Write("{0:0.#####} {0:0.#####} {0:0.#####} {0:0.#####} {0:0.#####}", a, a, a, a, a));
and also tried to change the culture globally:
System.Threading.Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
But the first one '{0:0.#####}' resulted in comma separator (1,05789), and the second one 'Thread' in CS0120: An object reference is required for the non-static field, method, or property.
And another problem is that:
f.Write("{0:0.#####} {0:0.#####} ...", a, a, ...);
duplicates the first object after the string, so I get all of numbers as 'a', even if I write
f.Write("{0:0.#####} {0:0.#####} ...", a, b, ...);
The problem with your last example:
Is that the part of the format strings before the colons is an index into the array of formatting parameters, so if you use all zeros, you will only get a, the 0'th parameter. Instead use
Here
{1:0.#####}
will use b, etc.Unless your code is highly performance critical, my preferred way of formatting the strings in the invariant culture would be to use the method System.FormattableString.Invariant to do string interpolation in the invariant culture: