fork download
  1. #include <limits.h>
  2. #include <locale.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. size_t commafmt(char *buf, /* Buffer for formatted string */
  8. int bufsize, /* Size of buffer */
  9. long N) /* Number to convert */
  10. {
  11. const struct lconv *fmt_info = localeconv();
  12. int places = 0;
  13. int i, len = 1, posn = 1, sign = 1;
  14. char *ptr = buf + bufsize - 1;
  15.  
  16. if (2 > bufsize)
  17. {
  18. ABORT: *buf = '\0';
  19. return 0;
  20. }
  21.  
  22. *ptr-- = '\0';
  23. --bufsize;
  24. if (0L > N)
  25. {
  26. sign = -1;
  27. N = -N;
  28. }
  29.  
  30. for (; len <= bufsize; ++len, ++posn)
  31. {
  32. *ptr-- = (char)((N % 10L) + '0');
  33. if (0L == (N /= 10L))
  34. break;
  35. if (fmt_info->grouping[places] && 0 == (posn % fmt_info->grouping[places]))
  36. {
  37. if (fmt_info->grouping[places + 1] != '\0')
  38. places = fmt_info->grouping[places + 1] == CHAR_MAX ? 0 : places + 1;
  39. for (i = 0; fmt_info->thousands_sep[i]; i++, ++len) {
  40. *ptr-- = fmt_info->thousands_sep[i];
  41. if (len >= bufsize)
  42. goto ABORT;
  43. }
  44. }
  45. if (len >= bufsize)
  46. goto ABORT;
  47. }
  48.  
  49. if (0 > sign)
  50. {
  51. if (len >= bufsize)
  52. goto ABORT;
  53. for (i = 0; fmt_info->negative_sign[i]; ++i) {
  54. *ptr-- = fmt_info->negative_sign[i];
  55. if (++len >= bufsize)
  56. goto ABORT;
  57. }
  58. }
  59.  
  60. memmove(buf, ++ptr, len + 1);
  61. return (size_t)len;
  62. }
  63.  
  64. int main() {
  65. char buffer[16];
  66.  
  67. setlocale(LC_ALL, "");
  68. commafmt(buffer, sizeof(buffer), -12345678);
  69.  
  70. printf("%s\n", buffer);
  71. return 0;
  72. }
Success #stdin #stdout 0s 11072KB
stdin
Standard input is empty
stdout
-12,345,678