Thread: format numbers output?

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    16

    format numbers output?

    hey, is there any way that i can format the output of the numbers, like a print mask or something?

    im printing out dollar ammounts, and right now it is say...$1000, is there any way to make it print $1,000...and other numbers such as $1,000,000,000 or something? thanks for your help

  2. #2
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Code:
    void
    printNumber (int num) {
    
        //big enough to hold number
       char s_num[100];
       // s_num length
       int len = 0; 
       
       sprintf( s_num, "%d", num );
       
       len = strlen(s_num);
          
       printf("$");
       for (int i=0;i<len;i++) {
          
          printf("%c", s_num[i]);
          
          // if we must print a ","
          if ((len-(i+1))%3==0 && len-i!=1) 
             printf(",");
       }
       printf("\n");
    }

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Very C.

    As I said in your other post. Another option is to use stringstreams and substrings.
    Sent from my iPadŽ

  4. #4
    Registered User
    Join Date
    Feb 2006
    Posts
    65
    This prints out $12,345.68:
    Code:
        std::cout.imbue(std::locale("en_US"));
        std::cout << std::fixed << std::setprecision(2);
        std::cout << "$" << 12345.678 << std::endl;
    (Don't forget that setprecision requires "#include <iomanip>")

    Note that if you ever need to translate this program and handle other currency formats the only thing you need to change the "en_US" string.. and the dollar symbol. No need to look up the decimal and thousands separators from some reference.

  5. #5
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Er... I tryed a better C++ solution, but couldn´t find anything to help me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Numbers in Text Format
    By deb_cal2 in forum C Programming
    Replies: 14
    Last Post: 01-24-2008, 04:23 AM
  2. Can we input negative numbers in the output windiw
    By hitesh1511 in forum C Programming
    Replies: 1
    Last Post: 08-22-2006, 12:07 AM
  3. Compression/Decompression Wave File and MP3
    By cindy_16051988 in forum Projects and Job Recruitment
    Replies: 51
    Last Post: 04-29-2006, 06:25 AM
  4. output format: screen vs .txt
    By -JM in forum C++ Programming
    Replies: 7
    Last Post: 04-20-2006, 08:05 PM
  5. Seeking Format Advice
    By PsychoBrat in forum Game Programming
    Replies: 3
    Last Post: 10-05-2005, 05:41 AM