Menu

Formatting Currency

2002-12-14
2012-09-26
  • Nobody/Anonymous

    I looked through the standard C\C++ libraries for a function to format currency, but I couldn't find one. This is what I have so far:

    #########BEGIN CODE
    //Output is written to the format buffer (1st parameter);
    //the format buffer is returned as a convenience
    char* formatCurrency(char* format, double curr)
    {

        long dollars = (long)floor(curr);
        long cents = (long)((curr-dollars) * 100);

        //convert longs to strings
        char szDollars[50];

        //we need to be able to change what szCents refers
        //to if we modify it; and we want to do it all on the
        //stack
        char szAlloc[50];
        char* szCents = szAlloc; //still on the STACK
       
        _ltoa(dollars, szDollars, 10);
        _ltoa(cents, szCents, 10);

        //possibly preppend a "0" to the cents string
        if(cents < 10) //there would be no zero at end
        {
            char* oldCents = szCents;
           
            //allocate some more char[] space on the stack
            char szAlloc[50];
            szCents = szAlloc; //a new array

            sprintf(szCents, "0%s", oldCents);
        }

        strcpy(format, "");
        //format the string to a dollar format ($#0.00);
        sprintf(format, "$%s.%s", szDollars, szCents );

        return format;
    }

    #########END CODE

    This code compiles and works fine, but it's pretty slow. How can I make this more efficient?

     
    • Nobody/Anonymous

      use compiler optimizations

       
    • Nobody/Anonymous

      Change the whole formatCurrency() function to:

      sprintf(format "$%.2f", curr);

      ...and read up on printf formatting...

      BlakJak :]

       
      • Nobody/Anonymous

        should be

        sprintf(format, "$%.2f", curr);

        forgot the comma....

        BlakJak :]

         
    • Nobody/Anonymous

      Thanks. I'm not even remotely fluent in sprintf/printf formatting.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.