Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
How can I print numbers with commas separating the thousands? What about currency formatted numbers?
How can I print numbers with commas separating the thousands? What about currency formatted numbers?
✍: Guest
The functions in <locale.h> begin to provide some support for these operations, but there is no standard C function for doing either task. (In Standard C, the only thing printf does in response to a custom locale setting is to change its decimal-point character.)
POSIX specifies a strfmon function for formatting monetary quantities in a locale-appropriate way, and that the apostrophe flag in a numeric printf format specifier (e.g. %'d, %'f) requests comma-separated digits.
Here is a little routine for formatting comma-separated numbers, using the locale's thousands separator, if available:
#include <locale.h>
char *commaprint(unsigned long n)
{
static int comma = '\0';
static char retbuf[30];
char *p = &retbuf[sizeof(retbuf)-1];
int i = 0;
if(comma == '\0') {
struct lconv *lcp = localeconv();
if(lcp != NULL) {
if(lcp->thousands_sep != NULL &&
*lcp->thousands_sep != '\0')
comma = *lcp->thousands_sep;
else comma = ',';
}
}
*p = '\0';
do {
if(i%3 == 0 && i != 0)
*--p = comma;
*--p = '0' + n % 10;
n /= 10;
i++;
} while(n != 0);
return p;
}
(A better implementation would use the grouping field of the lconv structure, rather than assuming groups of three digits. A safer size for retbuf might be 4*(sizeof(long)*CHAR_BIT+2)/3/3+1;
2015-11-02, 1563👍, 0💬
Popular Posts:
What is the purpose of Replication ? Replication is way of keeping data synchronized in multiple dat...
How do I use a scriptlet to initialize a newly instantiated bean? A jsp:useBean action may optionall...
.NET INTERVIEW QUESTIONS - How to prevent my .NET DLL to be decompiled? By design .NET embeds rich M...
What is XSLT? XSLT is a rule based language used to transform XML documents in to other file formats...
Can you have virtual functions in Java? Yes, all functions in Java are virtual by default. This is a...