简体   繁体   中英

Export a *.txt file convert commas to dots

I'm using this code to export a *.txt

TextWriter sw = new StreamWriter(@"C:\fiscal.txt");       

int rowcount = dataGridView1.Rows.Count;

for (int i = 0; i < rowcount - 1; i++)
{
    sw.Write("{0,-20}", dataGridView1.Rows[i].Cells[0].Value.ToString());       
}                

sw.Close();

My text file contain a value number with comma example 3,20

How can i change it? And to export it with dot 3.20

The simple fix would be to apply .NET/C# String.Replace(",", ".") method, but only if there are no other cases of using "," in that particular text; thus, the following line will do the job rather quick (best performance):

dataGridView1.Rows[i].Cells[0].Value.ToString().Replace(",", ".")

It will also work fine if the values are entered with, for example, dollar sign, like: $3,20 (would be converted into $3.20).

Alternatively, you may use Parse() (or TryParse()) methods in conjunction with CultureInfo class, which is sort of universal solution, but could be an "overkill" for this particular task, and also will take much longer to complete (ie will cause significant performance degradation). Also, the parsing could be a bit problematic in case the values are entered with a leading currency sign (like $3,20 mentioned above).

Hope this may help.

As this is monetary data you could convert the text to decimals using Decimal.TryParse with the culture set to one that has decimal commas (French say):

NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;

decimal result;
if (decimal.TryParse(text, style, new CultureInfo("fr-FR"), out result))
{

}

Then write it out using a culture that uses decimal points (English say):

string outputText = result.ToString("C", new CultureInfo("en-GB"));

Though this would have the side effect of changing the currency symbol. To make sure that stayed the same you'd have to clone the culture you were using for output and change it's currency symbol.

Use CultureInfo.InvariantCulture in ToString and Parse . So in your case it looks like this:

sw.Write("{0,-20}", dataGridView1.Rows[i].Cells[0].Value.ToString(CultureInfo.InvariantCulture));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM