0

I want to seperate a number with commas. I have tried many ways to do it. But didn't work.

Its already converted to a string and now i want to format the "tot".

GetData getData = new GetData();
string tot = Convert.ToString(getData.Total_Extra(month));
string totVal = (tot).ToString("N",new CultureInfo("en-US"));
LB2.Text = tot.ToString();
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
Mike
  • 1,017
  • 4
  • 19
  • 34

1 Answers1

2

You can convert your tot string to a numeric value and then use string.Format to get the desired format:

string tot = "19950000";
string output = string.Format("{0:n2}", Convert.ToInt32(tot));
Debug.WriteLine(output); //19,950,000.00 on my machine

or alternatively:

string output2 = Convert.ToInt32(tot).ToString("n2");

These are both culture specific, so might display differently on different users machines (Indian culture will display 1,99,50,000.00 for example).

If you want to force the three digit comma grouping then you can specify a culture to use:

string output2 = Convert.ToInt32(tot).ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
//19,950,000.00 on any machine

It sounds like your tot may not be a numeric value, so you should check this before trying to format it:

string tot = "19950000";
int totInt;
if (Int32.TryParse(tot, out totInt))
{
    string output = totInt.ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
    MessageBox.Show(output);
}
else
{
    MessageBox.Show("tot could not be parsed to an Int32");
}
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • I tried it too But creates an exception. I have upload the current code and please take a look. – Mike Aug 04 '16 at 09:30
  • GetData getData = new GetData(); string tot = Convert.ToString(getData.Total_Extra(month)); string totVal = string.Format("0:n2", Convert.ToInt32(tot)); LB2.Text = totVal.ToString(); – Mike Aug 04 '16 at 09:31
  • There you have tried to a float but i want to format a string value – Mike Aug 04 '16 at 09:35
  • Matt Wilko - I have tried with and without curly braces. I get exception saying wrong input type – Mike Aug 04 '16 at 09:36
  • @MattWilko : Mate that is the code you have put in your answer, I just want to say I have tried your code and that is working fine. The screenshot for OP :) – Sunil Kumar Aug 04 '16 at 09:50
  • Matt Wilko - I split your answer into two steps and now it's working. Thank you for the help – Mike Aug 04 '16 at 09:56