0

Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number

I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.

So if i have a string like this

546546555

desired output:

546,546,555

Other times, the number could be longer or shorter:

254654

desired output:

254,654

Is it possible to split in this manner then join with a comma?

tahnks!

EDIT:

Hi Everyone,

Thanks very much for your help.

To add to this post I also found a way to do this in SQL:

SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]

6
  • is it always a base-10 number? Commented Sep 24, 2012 at 14:33
  • 4
    Are you trying to do this...string.Format("{0:#,#}", 5465465555 ) Commented Sep 24, 2012 at 14:33
  • @JamesMichaelHare Hi James, it will always be an integer and never a decimal. Commented Sep 24, 2012 at 14:34
  • @GeneS Hi Gene, that looks solid, i will try that now, i am a novice programmer, didn't realize i had that formatt option Commented Sep 24, 2012 at 14:34
  • long.Parse("546546555").ToString("N0") Commented Sep 24, 2012 at 14:37

5 Answers 5

2

Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:

Example

int value = 546546555;
string displayValue = value.ToString("#,#");

See this MSDN page for different format values:

C - Currency format

D - Decimal format

E - Scientific format

F - Fixed point format

G - General format

N - Number format

P - Percent format

R - Round trip format

X - Hexadecimal format

Sign up to request clarification or add additional context in comments.

2 Comments

Do you know of a way to mimick this logic in sql server 2008?
That's a good question. I don't have an answer, but why not make it official and see what the community can come up with.
0

You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:

var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
   formatted = value.ToString("#,#");
}

Live example: http://rextester.com/FHO11833

Comments

0

Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:

string splitter(string tosplit, int num, string splitstring)
    {
        string output = "";
        for (int i = 0; i < tosplit.Length; i += num)
            if (i + num < tosplit.Length)
                output += tosplit.Substring(i, num) + ",";
            else
                output += tosplit.Substring(i);
        return output;
    }

Here, the output of splitter("546546555", 3, ",") would be 546,546,555

This would not be ideal for numbers though, as the other answers would cover this case perfectly.

Comments

0

Not very good code, but it works.

public static string GetString(string val, int number)
        {
            List<string> res = new List<string>();
            res.Add("");

            int counter = 0, i = 0;
            while (i < val.Length)
            {
                while (res[counter].Length < number && i < val.Length)
                {
                    res[counter] += val[i];
                    i++;
                }
                res.Add("");
                counter++;
            }

            return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
        }

val - your input string number - number of characters you want to split, equals to 3 in your case

Comments

0

Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.

        var val = 12345678;
        CultureInfo c = CultureInfo.CurrentCulture;
        Application.CurrentCulture = new CultureInfo("EN-us");
        var s = String.Format("{0:#,#}", val);
        Application.CurrentCulture = new CultureInfo("ES-es");
        var i = String.Format("{0:#,#}", val);
        Application.CurrentCulture = c;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.