How to add commas to a number...

Ok I have yet another dilemma... I dont know how to add commas to an unknown number, (eg. If the user entered 12000 i need it to cout as 12,000)

I have it in both double and string form.

And i know i have to count backwards and enter a comma every three numbers, but the problem is i dont know how to code that.

Please help, and remember the number is unknown so it has to work for every number >= 1000

I would submit the code i have so far but i am on my iphone and dont want to type 100+ lines of code on such a small keyboard.
So, as far as I understood, you have a number like that: abc....afrsd...000...0000. Where abc...afrsd are figures and after that figures you have 000...00 and you want to put a comma between the figures which are different from 0 and the 0 figures. Am I right?
If so, is not so hard. You said that you have the number in a string form. This is good.
First of all, you get the length of the string with strlen function and then you initialize the first component after the last component of the string your_string[strlen(your_string)+1] = '0' with 0 as you see. Then you initialize the next component with NULL character, to finish the string: your_string[strlen(your_string)+2]='\0'.
Now you use a loop which find you the first 0 near the figures:
1
2
3
4
 for(i=strlen(your_string); i>=0; i--)
{ if(your_string[i]!='0')
    break;
}

Now you have found the last figure. For example if you have 12323400000, the program found you the figure 4.

After that, you get the next 0, your_string[i+1]="," and replace this component with comma. You print the string and that's it. If you want to work with many numbers, you can put all these instructions in a loop. G - Luck.
HI ,
You can use the find function of the string where you can find the postion of the '0'
eg :
1
2
3
 string str = abcd0000435;
       size_ t i = str.find('0');
       str.insert(i -1 , ',');

Do you mean thousand separators?

If so, you don't have to do it backwards. Take your example : 12000

This is 5 digits long. 5 / 3 = 1 R 2. So you're got a group of 2 and then groups of three.

So display elems 0..1; then a comma; then elems 2..4

If you're using std::string, you need its length() and substr() methods

If not, you could used strlen() and strncpy()
^ You're right but maybe the brandonjconnor wants to add a comma to his string. That means to insert a comma in his string and then to print all the string with a comma in it. If brandonjconnor want just to print that string with a comma, your method is ok.
Topic archived. No new replies allowed.