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
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?
use compiler optimizations
Change the whole formatCurrency() function to:
sprintf(format "$%.2f", curr);
...and read up on printf formatting...
BlakJak :]
should be
sprintf(format, "$%.2f", curr);
forgot the comma....
BlakJak :]
Thanks. I'm not even remotely fluent in sprintf/printf formatting.