Is there a function that will add commas to large numbers?
For example if my input argument is 123456789 is there a function that will print it out as 123,456,789?
Thanks!!
Is there a function that will add commas to large numbers?
For example if my input argument is 123456789 is there a function that will print it out as 123,456,789?
Thanks!!
That would be incredibly easy to write. I'd suggest doing it yourself.
FAQ
"The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.
"If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.
Almost sounds like homework...
it ALMOST is homework. It just doesn't sound all that easy. I've seen something like take the number and divide it by 1,000. But I'm not sure how exactly to do it.
> 123456789
123456789 / 1000 = 123456
123456789 % 1000 = 789
Rinse and repeat until x/1000 is zero
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
>Is there a function that will add commas to large numbers?
If you look around a bit, you'll find a function that I've posted before which does precisely this.
[edit]
I couldn't find it, so here's the basic idea:
[/edit]Code:#include <iostream> #include <string> bool third_char ( int pos ) { return pos != 0 && pos % 3 == 0; } std::string commaize ( unsigned long val ) { std::string buff; int i = 0; // The workhorse algorithm. Use of std::string::insert // is okay since the string will not be very long even // for large unsigned long values. If you end up using // an arbitrary length number, changing this to use a // more suitable buffer container would be advisable do { if ( third_char ( i++ ) ) buff.insert ( buff.begin(), ',' ); buff.insert ( buff.begin(), '0' + val % 10 ); } while ( ( val /= 10 ) != 0 ); return buff; } int main() { std::cout<< commaize ( 1234567890 ) <<std::endl; }
Last edited by Prelude; 11-04-2003 at 09:00 AM.
My best code is written with the delete key.
Thanks Prelude & Salem!