I wish to output large numbers with thousand-separators (commas or spaces) — basically the same as in How to display numeric in 3 digit grouping but using printf
in C (GNU, 99).
If printf does not support digit grouping natively, how can I achieve this with something like printf("%s", group_digits(number))
?
It must support negative integers and preferably floats, too.
If you can use POSIX printf, try
#include <locale.h>
setlocale(LC_ALL, ""); /* use user selected locale */
printf("%'d", 1000000);
Here is a compact way of doing it:
// format 1234567.89 -> 1 234 567.89
extern char *strmoney(double value){
static char result[64];
char *result_p = result;
char separator = ' ';
size_t tail;
snprintf(result, sizeof(result), "%.2f", value);
while(*result_p != 0 && *result_p != '.')
result_p++;
tail = result + sizeof(result) - result_p;
while(result_p - result > 3){
result_p -= 3;
memmove(result_p + 1, result_p, tail);
*result_p = separator;
tail += 4;
}
return result;
}
For example, a call to strmoney(1234567891.4568)
returns the string "1 234 567 891.46"
. You can easily replace the space with another separator (such as a comma) by changing the separator
variable at the top of the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With