423,867 Members | 1,958 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,867 IT Pros & Developers. It's quick & easy.

how to formatting and printing comma just use argument which returned from function.

P: 1
I would like to output values with commas which formatting like as below.
may i know if any idea to make this kind of program?

int total sum = 123456;
printf("Total sum: %d \n",comma_function(total_sum));

**result**

Total sum: 123,456
Jun 13 '18 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,196
You can use an algorithm. I would write a function that does the reformatting and returns the formatted number. Then have the calling function display the formatted number. You don't want the display in the function because the function would now be doing more than one thing and this is a design no-no.

The function should have two arguments, the number and a pointer to the formatted result. This keeps the function out of the memory allocation business.

The algorithm is:
Is the number 0. If yes you are done.

I usually see this done when formatting money values $123,456.78. To do this your original number must be in pennies.

int data = 12345678;

cout << '$';

cout << data / 100000 << ','; //this is 123

data = data %100000; //removes the 100,000's. Remainder is 45678

cout << data / 100; //this is 456

data = data % 100; //removes the 100's. Remainder is 78. Anything less then 100 is pennies

cout << '.';

cout << data << endl;

You should now have $123,456.78.

Does this help?
Jun 13 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.