From cf13cb256bd7c58a3df4ed899d3765ebd1a0a8c5 Mon Sep 17 00:00:00 2001 From: David Anderson Date: Tue, 11 Aug 2015 14:18:06 -0700 Subject: [PATCH] lib: add function for formatting numbers w/ digit grouping --- lib/str_util.cpp | 31 +++++++++++++++++++++++++++++++ lib/str_util.h | 1 + 2 files changed, 32 insertions(+) diff --git a/lib/str_util.cpp b/lib/str_util.cpp index e0f78b97ec..ad57e6151e 100644 --- a/lib/str_util.cpp +++ b/lib/str_util.cpp @@ -756,3 +756,34 @@ vector split(string s, char delim) { } return result; } + +char *comma_print(unsigned long n) { + static char comma = 0; + static char retbuf[30]; + char *p = &retbuf[sizeof(retbuf)-1]; + int i = 0; + + if (!comma) { + struct lconv *lcp = localeconv(); + if (lcp) { + if (lcp->thousands_sep != NULL && *lcp->thousands_sep) { + 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); + + return p; +} diff --git a/lib/str_util.h b/lib/str_util.h index ea2eec7f29..e890b59a29 100644 --- a/lib/str_util.h +++ b/lib/str_util.h @@ -101,4 +101,5 @@ extern const char* batch_state_string(int state); extern void strip_translation(char* p); extern std::vector split(std::string, char delim); +extern char* comma_print(unsigned long); #endif