Reputation: 2125
I'm writing a csv converter to convert a text document of transactions into a csv document and I've run into a little problem..
foreach (var transaction in transactions)
{
output.Append(
string.Format("{0:dd/MM/yy},{1},{2},{3},{4:0.##},{5}",
transaction.Date,
transaction.Payee,
transaction.Category,
transaction.Memo,
transaction.Outflow,
transaction.Inflow));
output.AppendLine();
}
This all works fine, the small issue I have is that the Outflow
property is a float and my locale uses commas as the decimal delimiter, which is obviously quite a problem in a CSV so instead of getting let's say 10.50 it will output 10,50, is there any easy way to solve this?
Upvotes: 1
Views: 807
Reputation: 24390
You can specify invariant culture which uses .
:
foreach (var transaction in transactions)
{
output.Append(
string.Format("{0:dd/MM/yy},{1},{2},{3},{4},{5}",
transaction.Date,
transaction.Payee,
transaction.Category,
transaction.Memo,
transaction.Outflow.ToString("F2", CultureInfo.InvariantCulture),
transaction.Inflow));
output.AppendLine();
}
On a side-note, use decimal
for money not float
:
decimal
is base 10 so it can represent fractional currency values like 0.1
exactly, float
is base 2 and it can't. using float
will result in strange rounding errors, and comparisons will not work as expected. Consider this:
float a = 3.6f, b = 0.1f, expected = 3.7f;
float sum = a + b;
Console.WriteLine(sum == expected); // false
This will output false because sum will actually be 3.69999981
You can read more on the subject from this C# in Depth excerpt.
Upvotes: 5
Reputation: 884
You can replace the , by . like this:
transaction.Outflow.ToString().Replace(',','.');
Upvotes: -2