how to display 12345 as 12,345 ??

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • news.hku.hk

    how to display 12345 as 12,345 ??

    suppose i have:

    int price1 = 35000;
    int price2 = 600;
    int price3 = 8765;
    int price4 = 120000;
    int price5 = 3800000;

    and i want to output to screen the following:

    35,000
    600
    8,765
    120,000
    3,800,000

    what should i do ?? any good function to do this ??


  • Marcin Kalicinski

    #2
    Re: how to display 12345 as 12,345 ??

    U¿ytkownik "news.hku.h k" <billychu@hkusu a.hku.hk> napisa³ w wiadomo¶ci
    news:408d1077@n ewsgate.hku.hk. ..[color=blue]
    > suppose i have:
    >
    > int price1 = 35000;
    > int price2 = 600;
    > int price3 = 8765;
    > int price4 = 120000;
    > int price5 = 3800000;
    >
    > and i want to output to screen the following:
    >
    > 35,000
    > 600
    > 8,765
    > 120,000
    > 3,800,000
    >
    > what should i do ?? any good function to do this ??[/color]

    Not in the standard. You'll have to do it yourself. I believe it is quite
    simple.

    regards,
    Marcin



    Comment

    • John Ericson

      #3
      Re: how to display 12345 as 12,345 ??

      "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message
      news:408d1077@n ewsgate.hku.hk. ..[color=blue]
      > suppose i have:
      >
      > int price1 = 35000;
      > int price2 = 600;
      > int price3 = 8765;
      > int price4 = 120000;
      > int price5 = 3800000;
      >
      > and i want to output to screen the following:
      >
      > 35,000
      > 600
      > 8,765
      > 120,000
      > 3,800,000
      >
      > what should i do ?? any good function to do this ??
      >
      >[/color]

      You could look up facets, and check out Dinkumware.


      Comment

      • JKop

        #4
        Re: how to display 12345 as 12,345 ??



        I've done this before. I've adapted it for the purpose of this post, but
        here goes (Check for bugs before you use it!):


        char szBuffer[30]; //Global Variable

        char* GenerateString( unsigned long);

        int main(void)
        {
        cout << GenerateString( 12345);
        }


        char* GenerateString( unsigned long Numbr)
        {
        szBuffer[29] = '\0';

        char* pChar = &m_szBuffer[28];

        unsigned long char_counter = 0;
        unsigned long comma_counter = 0;
        unsigned long nResult; //will be initialized
        unsigned long nTempValue = Numbr;

        for(;;)
        {
        nResult = 0;

        //I used to use the method below, but it's FAR too slow
        /*
        while ( nTempValue >= 10 )
        {
        nTempValue -= 10;
        nResult += 1;
        }*/

        nResult = nTempValue / 10;
        nTempValue %= 10;

        *pChar = ( ( '0' ) + ( nTempValue ) );
        pChar -= 1;


        char_counter +=1;

        nTempValue = nResult; //Very Important!

        if (!nTempValue) break; //This line prevents ",345" being
        generated

        char_counter += 1;


        if ( comma_counter == 3 )
        {
        *pChar = ',';
        pChar -= 1;
        char_counter += 1;
        comma_counter = 0;
        }
        } //End of "For"

        return pChar;

        }


        Hope that helps. Also, you may try incorporating it into a class ( I did! )
        and also overide the ostream "<<" operator! That'd be dead handy. I'd post
        the class I wrote for it but it had a very specific purpose other than just
        genrating these strings.


        -JKop

        Comment

        • pembed2003

          #5
          Re: how to display 12345 as 12,345 ??

          "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message news:<408d1077@ newsgate.hku.hk >...[color=blue]
          > suppose i have:
          >
          > int price1 = 35000;
          > int price2 = 600;
          > int price3 = 8765;
          > int price4 = 120000;
          > int price5 = 3800000;
          >
          > and i want to output to screen the following:
          >
          > 35,000
          > 600
          > 8,765
          > 120,000
          > 3,800,000
          >
          > what should i do ?? any good function to do this ??[/color]

          Hi,
          I am new to C++ too so my solution might not be very good. Anyway, I
          will try something like:

          void _display_number (int v, int n){
          if(v >= 1000){
          int r = v % 1000;
          _display_number (v / 1000,n);
          printf(",%03d", r); // how to translate that into
          std::cout<<...?
          }else{
          printf("%s%d\n" ,n ? "-":"",v);
          }
          }

          void display_number( int v){
          _display_number (v < 0 ? -v : v,v < 0);
          }

          int main(int argc,char** argv){
          display_number( 35000);
          display_number( 600);
          display_number( 8765);
          display_number( 120000);
          display_number( 3800000);
          display_number(-3800000);
          }

          The program prints something like:

          35,000
          600
          8,765
          120,000
          3,800,000
          -3,800,000

          HTH. I am here to learn as well so if anyone can help me improve the
          program, I am happy to see it. Thanks!

          Comment

          • John Ericson

            #6
            Re: how to display 12345 as 12,345 ??


            "JKop" <NULL@NULL.NULL > wrote in message
            news:CUcjc.5713 $qP2.13751@news .indigo.ie...[color=blue]
            >
            >
            > I've done this before. I've adapted it for the purpose of[/color]
            this post, but[color=blue]
            > here goes (Check for bugs before you use it!):
            >
            >
            > char szBuffer[30]; //Global Variable
            >
            > char* GenerateString( unsigned long);
            >
            > int main(void)
            > {
            > cout << GenerateString( 12345);
            > }
            >
            >
            > char* GenerateString( unsigned long Numbr)
            > {
            > szBuffer[29] = '\0';
            >
            > char* pChar = &m_szBuffer[28];
            >
            > unsigned long char_counter = 0;
            > unsigned long comma_counter = 0;
            > unsigned long nResult; //will be initialized
            > unsigned long nTempValue = Numbr;
            >
            > for(;;)
            > {
            > nResult = 0;
            >
            > //I used to use the method below, but it's FAR too[/color]
            slow[color=blue]
            > /*
            > while ( nTempValue >= 10 )
            > {
            > nTempValue -= 10;
            > nResult += 1;
            > }*/
            >
            > nResult = nTempValue / 10;
            > nTempValue %= 10;
            >
            > *pChar = ( ( '0' ) + ( nTempValue ) );
            > pChar -= 1;
            >
            >
            > char_counter +=1;
            >
            > nTempValue = nResult; //Very Important!
            >
            > if (!nTempValue) break; //This line prevents ",345"[/color]
            being[color=blue]
            > generated
            >
            > char_counter += 1;
            >
            >
            > if ( comma_counter == 3 )
            > {
            > *pChar = ',';
            > pChar -= 1;
            > char_counter += 1;
            > comma_counter = 0;
            > }
            > } //End of "For"
            >
            > return pChar;
            >
            > }
            >
            >
            > Hope that helps. Also, you may try incorporating it into a[/color]
            class ( I did! )[color=blue]
            > and also overide the ostream "<<" operator! That'd be dead[/color]
            handy. I'd post[color=blue]
            > the class I wrote for it but it had a very specific[/color]
            purpose other than just[color=blue]
            > genrating these strings.
            >
            >
            > -JKop[/color]

            How about (untested code, and YMMV)

            #include <iostream>
            #include <locale>

            int main()
            {
            using namespace std;
            cout.imbue(loca le("English")) ;
            cout << 12345 << '\n';
            }

            ;) JE


            Comment

            • news.hku.hk

              #7
              Re: how to display 12345 as 12,345 ??

              thanks for all of your's help
              but i still can't grasp the idea of the algorithm
              maybe could anyone explain in words(preferabl y with c++ codes) that how the
              algorithm works ??
              Thanks

              "pembed2003 " <pembed2003@yah oo.com> wrote in message
              news:db593abd.0 404261130.2a02b 059@posting.goo gle.com...[color=blue]
              > "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message[/color]
              news:<408d1077@ newsgate.hku.hk >...[color=blue][color=green]
              > > suppose i have:
              > >
              > > int price1 = 35000;
              > > int price2 = 600;
              > > int price3 = 8765;
              > > int price4 = 120000;
              > > int price5 = 3800000;
              > >
              > > and i want to output to screen the following:
              > >
              > > 35,000
              > > 600
              > > 8,765
              > > 120,000
              > > 3,800,000
              > >
              > > what should i do ?? any good function to do this ??[/color]
              >
              > Hi,
              > I am new to C++ too so my solution might not be very good. Anyway, I
              > will try something like:
              >
              > void _display_number (int v, int n){
              > if(v >= 1000){
              > int r = v % 1000;
              > _display_number (v / 1000,n);
              > printf(",%03d", r); // how to translate that into
              > std::cout<<...?
              > }else{
              > printf("%s%d\n" ,n ? "-":"",v);
              > }
              > }
              >
              > void display_number( int v){
              > _display_number (v < 0 ? -v : v,v < 0);
              > }
              >
              > int main(int argc,char** argv){
              > display_number( 35000);
              > display_number( 600);
              > display_number( 8765);
              > display_number( 120000);
              > display_number( 3800000);
              > display_number(-3800000);
              > }
              >
              > The program prints something like:
              >
              > 35,000
              > 600
              > 8,765
              > 120,000
              > 3,800,000
              > -3,800,000
              >
              > HTH. I am here to learn as well so if anyone can help me improve the
              > program, I am happy to see it. Thanks![/color]


              Comment

              • rossum

                #8
                Re: how to display 12345 as 12,345 ??

                On Mon, 26 Apr 2004 21:37:07 +0800, "news.hku.h k"
                <billychu@hkusu a.hku.hk> wrote:
                [color=blue]
                >suppose i have:
                >
                >int price1 = 35000;
                >int price2 = 600;
                >int price3 = 8765;
                >int price4 = 120000;
                >int price5 = 3800000;
                >
                >and i want to output to screen the following:
                >
                >35,000
                >600
                >8,765
                >120,000
                >3,800,000
                >
                >what should i do ?? any good function to do this ??
                >[/color]
                Yet another alternative. This one converts the number into a string
                and puts the commas into the string. Not necessarily better, just
                different.

                rossum


                #include <string>
                #include <sstream>
                #include <iostream>
                #include <cstdlib>

                std::string comma(int num) {
                // Deal with negatives
                if(num < 0) { return "-" + comma(std::abs( num)); }

                // Convert number to string
                std::stringstre am ss;
                ss << num;
                std::string num_string = ss.str();

                // Insert a comma every third position
                for (int i = num_string.leng th() - 3; i > 0; i -= 3) {
                num_string.inse rt(i, 1, ',');
                } // end for

                return num_string;
                } // end comma()

                //---------------------------

                int main() {
                std::cout << comma(-3800000) << '\n'
                << comma(-120000) << '\n'
                << comma(-35000) << '\n'
                << comma(-8765) << '\n'
                << comma(-600) << '\n'
                << comma(-50) << '\n'
                << comma(-4) << '\n'
                << comma(0) << '\n'
                << comma(4) << '\n'
                << comma(50) << '\n'
                << comma(600) << '\n'
                << comma(8765) << '\n'
                << comma(35000) << '\n'
                << comma(120000) << '\n'
                << comma(3800000) << std::endl;
                return EXIT_SUCCESS;
                } // end main()





                --

                The Ultimate Truth is that there is no Ultimate Truth

                Comment

                • Siemel Naran

                  #9
                  Re: how to display 12345 as 12,345 ??

                  "John Ericson" <jericwahabison @pacbell.net> wrote in message news:Eijjc.1921

                  This is a good solution. Not sure why everyone is re-inventing the wheel.
                  [color=blue]
                  > using namespace std;
                  > cout.imbue(loca le("English")) ;
                  > cout << 12345 << '\n';[/color]

                  But, is there a locale named "English"?


                  Comment

                  • news.hku.hk

                    #10
                    Re: how to display 12345 as 12,345 ??

                    Thanks, i see your point
                    but how to return to the original state??
                    because i just want to insert the comma in someline while later i just want
                    to display ordinary numbers.

                    also, from your quotation, if i add one more cout line after cout << 12345
                    <<'\n';

                    i.e. cout << 543532 << '\n';
                    there will be runtime error.......wha t's up ??

                    "Siemel Naran" <SiemelNaran@RE MOVE.att.net> wrote in message
                    news:vNIjc.5671 8$um3.1096370@b gtnsc04-news.ops.worldn et.att.net...[color=blue]
                    > "John Ericson" <jericwahabison @pacbell.net> wrote in message[/color]
                    news:Eijjc.1921[color=blue]
                    >
                    > This is a good solution. Not sure why everyone is re-inventing the wheel.
                    >[color=green]
                    > > using namespace std;
                    > > cout.imbue(loca le("English")) ;
                    > > cout << 12345 << '\n';[/color]
                    >
                    > But, is there a locale named "English"?
                    >
                    >[/color]


                    Comment

                    • Siemel Naran

                      #11
                      Re: how to display 12345 as 12,345 ??

                      "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message news:408f9591
                      [color=blue]
                      > Thanks, i see your point
                      > but how to return to the original state??
                      > because i just want to insert the comma in someline while later i just[/color]
                      want[color=blue]
                      > to display ordinary numbers.[/color]

                      Haven't tried it yet, but approaches I suggest is: (1) use 2 locales, and
                      imbue cout with first locale when you want num_put to put comma symbols and
                      default locale when you don't want comma symbols, (2) create a new type
                      Amount for which operator<<(ostr eam&, Amount) uses num_put for Amount
                      objects and this num_put uses comma symbols. See my response in the thread
                      with subject "convert hex to oct" for this imbue, use_facet, etc. But there
                      was a C++ magazine that had and maybe still has lots of articles on these
                      ideas, and I think the articles were by Plauger, so maybe you can browse for
                      that too.
                      [color=blue]
                      > also, from your quotation, if i add one more cout line after cout << 12345
                      > <<'\n';
                      >
                      > i.e. cout << 543532 << '\n';
                      > there will be runtime error.......wha t's up ??[/color]

                      No error. I don't know what quotation you're talking about.

                      [color=blue]
                      > "Siemel Naran" <SiemelNaran@RE MOVE.att.net> wrote in message
                      > news:vNIjc.5671 8$um3.1096370@b gtnsc04-news.ops.worldn et.att.net...[color=green]
                      > > "John Ericson" <jericwahabison @pacbell.net> wrote in message[/color]
                      > news:Eijjc.1921[color=green]
                      > >
                      > > This is a good solution. Not sure why everyone is re-inventing the[/color][/color]
                      wheel.[color=blue][color=green]
                      > >[color=darkred]
                      > > > using namespace std;
                      > > > cout.imbue(loca le("English")) ;
                      > > > cout << 12345 << '\n';[/color]
                      > >
                      > > But, is there a locale named "English"?
                      > >
                      > >[/color]
                      >
                      >[/color]


                      Comment

                      • Joe Hotchkiss

                        #12
                        Re: how to display 12345 as 12,345 ??

                        news.hku.hk wrote:[color=blue]
                        > Thanks, i see your point
                        > but how to return to the original state??
                        > because i just want to insert the comma in someline while later i
                        > just want to display ordinary numbers.[/color]

                        cout.imbue(loca le("C"));

                        <snip>[color=blue][color=green][color=darkred]
                        >>> cout.imbue(loca le("English")) ;[/color][/color][/color]
                        <snip>[color=blue][color=green]
                        >> But, is there a locale named "English"?[/color][/color]

                        Since the sample works fine for me, I would assume there is. At least for my
                        compiler.
                        Why not try it and see with your compiler?

                        --
                        Regards,

                        Joe Hotchkiss,


                        XXXXXXXXXXXXXXX XXXXXXXXXX
                        X joe.hotchkiss X
                        X at baesystems.com X
                        XXXXXXXXXXXXXXX XXXXXXXXXX



                        Comment

                        • Jerry Coffin

                          #13
                          Re: how to display 12345 as 12,345 ??

                          "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message news:<408d1077@ newsgate.hku.hk >...[color=blue]
                          > suppose i have:
                          >
                          > int price1 = 35000;
                          > int price2 = 600;
                          > int price3 = 8765;
                          > int price4 = 120000;
                          > int price5 = 3800000;
                          >
                          > and i want to output to screen the following:
                          >
                          > 35,000
                          > 600
                          > 8,765
                          > 120,000
                          > 3,800,000
                          >
                          > what should i do ?? any good function to do this ??[/color]

                          You might want to look at commafmt.c at www.snippets.org.

                          --
                          Later,
                          Jerry.

                          The universe is a figment of its own imagination.

                          Comment

                          • E. Robert Tisdale

                            #14
                            Re: how to display 12345 as 12,345 ??

                            news.hku.hk wrote:
                            [color=blue]
                            > Suppose that I have:
                            >
                            > int price1 = 35000;
                            > int price2 = 600;
                            > int price3 = 8765;
                            > int price4 = 120000;
                            > int price5 = 3800000;
                            >
                            > and that I want to output to screen the following:
                            >
                            > 35,000
                            > 600
                            > 8,765
                            > 120,000
                            > 3,800,000
                            >
                            > What should I do? Are there any good functions to do this?[/color]

                            [color=blue]
                            > cat main.cc[/color]
                            #include <iostream>
                            #include <iomanip>

                            class Price {
                            private:
                            // representation
                            int I;
                            public:
                            // functions
                            friend
                            std::ostream& operator<<(std: :ostream& os, const Price& i);
                            // operators
                            // implicit
                            operator int(void) const { return I;}
                            operator int(void) { return I;}
                            // constructors
                            Price(int i = 0): I(i) { }
                            };

                            inline
                            std::ostream& operator<<(std: :ostream& os, const Price& i) {
                            int q = (int)i/1000;
                            int r = (int)i%1000;
                            if (0 < q)
                            os << Price(q) << ','
                            << std::setfill('0 ') << std::setw(3) << r;
                            else
                            os << r;
                            return os;
                            }

                            int main(int argc, char* argv[]) {
                            const
                            int price[] = {35000, 600, 8765, 120000, 3800000};
                            const
                            size_t n = sizeof(price)/sizeof(price[0]);
                            for (size_t j = 0; j < n; ++j)
                            std::cout << Price(price[j]) << std::endl;
                            return 0;
                            }
                            [color=blue]
                            > g++ -Wall -ansi -pedantic -o main main.cc
                            > ./main[/color]
                            35,000
                            600
                            8,765
                            120,000
                            3,800,000

                            Comment

                            • rossum

                              #15
                              Re: how to display 12345 as 12,345 ??

                              On 26 Apr 2004 12:30:35 -0700, pembed2003@yaho o.com (pembed2003)
                              wrote:

                              [snip OP][color=blue]
                              >
                              >Hi,
                              >I am new to C++ too so my solution might not be very good. Anyway, I
                              >will try something like:
                              >[/color]
                              Show what headers you are including. Code should be compilable as is,
                              just cut and paste.
                              [color=blue]
                              >void _display_number (int v, int n){[/color]
                              Avoid leading underscores, they are used internally by compilers so if
                              you pick the wrong name you will get a compilation error. Since
                              compilers differ this might also make your code non-portable.
                              Trailing underscores are safer and hence better. So change
                              _display_number () to display_number_ ().

                              You have a good self explanatory name for the function, but you use
                              short cryptic names for the two parameters. Better to change v to
                              value and n to is_negative so they are more self explanatory.

                              The second parameter is a yes/no flag so it is better to declare is as
                              a bool which gives a better indication of its purpose. It is possible
                              to eliminate this parameter by taking a slightly different approach to
                              the recursion.
                              [color=blue]
                              > if(v >= 1000){[/color]
                              Put a space between the if and the open bracket: if (value >= 1000) {.
                              This is to differentiate it from function calls. ^--added space
                              [color=blue]
                              > int r = v % 1000;[/color]
                              Another short cryptic variable name. Change it to something
                              meaningful.
                              [color=blue]
                              > _display_number (v / 1000,n);[/color]
                              Better to put a space after the comma which separates the parameters.
                              [color=blue]
                              > printf(",%03d", r); // how to translate that into
                              >std::cout<<... ?[/color]
                              Better to put a space after the second comma which separates the
                              parameters.

                              For cout look up the I/O manipulators.
                              [color=blue]
                              > }else{
                              > printf("%s%d\n" ,n ? "-":"",v);[/color]
                              The ternary operator ?: can make for unreadable code. Better to use
                              it sparingly. If you do use it then put spaces round both the '?' and
                              the ':' for clarity. Again spaces after any commas that separate
                              parameters are easier to read.

                              Are you really sure about that '\n' there? I hope that you
                              cut-and-pasted this rather than typed it from scratch.
                              [color=blue]
                              > }
                              >}
                              >
                              >void display_number( int v){
                              > _display_number (v < 0 ? -v : v,v < 0);[/color]
                              Where the ternary operator has a boolean expression it is better to
                              put the expression in brackets: (v < 0) ? -v : v to improve
                              readability. Again put a space after the parameter separating comma.[color=blue]
                              >}
                              >
                              >int main(int argc,char** argv){
                              > display_number( 35000);
                              > display_number( 600);
                              > display_number( 8765);
                              > display_number( 120000);
                              > display_number( 3800000);
                              > display_number(-3800000);[/color]

                              Main does not require a return value, but it is better style to
                              include it explicitly. I tend to use the EXIT_SUCCESS and
                              EXIT_FAILURE macros.
                              [color=blue]
                              >}
                              >
                              >The program prints something like:
                              >
                              >35,000
                              >600
                              >8,765
                              >120,000
                              >3,800,000
                              >-3,800,000
                              >
                              >HTH. I am here to learn as well so if anyone can help me improve the
                              >program, I am happy to see it. Thanks![/color]

                              Hope you find that useful.

                              rossum


                              --

                              The Ultimate Truth is that there is no Ultimate Truth

                              Comment

                              Working...