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, 1817👍, 0💬
Popular Posts:
How To Decrement Dates by 1? - MySQL FAQs - Introduction to SQL Date and Time Handling If you have a...
How To Enter Characters as HEX Numbers? - MySQL FAQs - Introduction to SQL Basics If you want to ent...
Which bit wise operator is suitable for turning on a particular bit in a number? The bitwise OR oper...
How To Control Vertical Alignment? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells By d...
What is AL.EXE and RESGEN.EXE? In the previous question you have seen how we can use resource files ...