From c0e6b3b3d2ee4ca10315cb45ea2caed8067bff3a Mon Sep 17 00:00:00 2001 From: David Anderson Date: Thu, 17 Sep 2015 13:48:04 -0700 Subject: [PATCH] client/manager: code shuffle to generalize comma_print() --- lib/str_util.cpp | 52 ++++++++++++++++++++++++++---------------------- lib/str_util.h | 7 +++++++ 2 files changed, 35 insertions(+), 24 deletions(-) diff --git a/lib/str_util.cpp b/lib/str_util.cpp index 156ce3ed9b..e1343e0b58 100644 --- a/lib/str_util.cpp +++ b/lib/str_util.cpp @@ -757,38 +757,42 @@ vector split(string s, char delim) { return result; } +NUM_FORMAT_CHARS nfc; + +static void get_format_chars() { + if (nfc.thousands_sep) return; +#ifdef _WIN32 + char buf[256]; + GetLocaleInfoA(NULL, LOCALE_STHOUSAND, buf, sizeof(buf)); + nfc.thousands_sep = buf[0]; + GetLocaleInfoA(NULL, LOCALE_SDECIMAL, buf, sizeof(buf)); + nfc.decimal_point = buf[0]; +#else + struct lconv *lcp = localeconv(); + if (lcp) { + if (lcp->thousands_sep != NULL && *lcp->thousands_sep) { + nfc.thousands_sep = *lcp->thousands_sep; + nfc.decimal_point = *lcp->decimal_point; + } else { + nfc.thousands_sep = ','; + nfc.decimal_point = '.'; + } + } +#endif +} + // convert number to string with thousands separators. // If nfrac is nonzero, following with fractional digits // string comma_print(double x, int nfrac) { - static char comma = 0, decimal_point; static char retbuf[30]; char *p = &retbuf[sizeof(retbuf)-1]; int i = 0; - if (!comma) { -#ifdef _WIN32 - char buf[256]; - GetLocaleInfoA(NULL, LOCALE_STHOUSAND, buf, sizeof(buf)); - comma = buf[0]; - GetLocaleInfoA(NULL, LOCALE_SDECIMAL, buf, sizeof(buf)); - decimal_point = buf[0]; -#else - struct lconv *lcp = localeconv(); - if (lcp) { - if (lcp->thousands_sep != NULL && *lcp->thousands_sep) { - comma = *lcp->thousands_sep; - decimal_point = *lcp->decimal_point; - } else { - comma = ','; - decimal_point = '.'; - } - } -#endif - } - *p = 0; + get_format_chars(); + unsigned long long n = x; // do fractional part if requested @@ -798,12 +802,12 @@ string comma_print(double x, int nfrac) { p -= nfrac+1; sprintf(p, "%.*f", nfrac, frac); p++; // skip 0 - *p = decimal_point; + *p = nfc.decimal_point; } do { if (i%3 == 0 && i != 0) { - *--p = comma; + *--p = nfc.thousands_sep; } *--p = '0' + n % 10; n /= 10; diff --git a/lib/str_util.h b/lib/str_util.h index f03cf88b05..a91213d6ae 100644 --- a/lib/str_util.h +++ b/lib/str_util.h @@ -101,5 +101,12 @@ extern const char* batch_state_string(int state); extern void strip_translation(char* p); extern std::vector split(std::string, char delim); + +struct NUM_FORMAT_CHARS { + char thousands_sep; + char decimal_point; +}; +extern NUM_FORMAT_CHARS nfc; extern std::string comma_print(double, int); + #endif