diff --git a/HISTORY b/HISTORY index 0f9ed87..a910a17 100644 --- a/HISTORY +++ b/HISTORY @@ -1,6 +1,7 @@ -Version 1.84 2025-12-23 +Version 1.84 2026-01-16 * fast_task_queue.h: add function free_queue_task_arg_offset + * add function double2str and double_to_comma_str Version 1.83 2025-11-15 * fast_task_queue.h: remove field finish_callback diff --git a/src/shared_func.c b/src/shared_func.c index 60e9734..313d336 100644 --- a/src/shared_func.c +++ b/src/shared_func.c @@ -3178,7 +3178,7 @@ key_t fc_ftok(const char *path, const int proj_id) return (((proj_id & 0xFF) << 24) | (hash_code & 0xFFFFFF)); } -static void add_thousands_separator(char *str, const int len) +static int add_thousands_separator(char *str, const int len) { int new_len; int addings; @@ -3191,7 +3191,7 @@ static void add_thousands_separator(char *str, const int len) if (len <= 3) { - return; + return len; } if (*str == '-') @@ -3227,6 +3227,8 @@ static void add_thousands_separator(char *str, const int len) add_count++; } } + + return new_len; } const char *int2str(const int n, char *buff, const bool thousands_separator) @@ -4523,3 +4525,33 @@ int fc_compare_int64_ptr(const int64_t *n1, const int64_t *n2) { return fc_compare_int64(*n1, *n2); } + +const char *double2str(const double d, const int scale, + char *buff, const bool thousands_separator) +{ + int len; + int front_len; + int tail_len; + int new_len; + char *point; + char fragment[32]; + + len = fc_ftoa(d, scale, buff); + *(buff + len) = '\0'; + if (!thousands_separator) { + return buff; + } + + if (scale <= 0) { + add_thousands_separator(buff, len); + return buff; + } + + tail_len = 1 + scale; + front_len = len - tail_len; + point = buff + front_len; + memcpy(fragment, point, tail_len + 1); + new_len = add_thousands_separator(buff, front_len); + memcpy(buff + new_len, fragment, tail_len + 1); + return buff; +} diff --git a/src/shared_func.h b/src/shared_func.h index d851405..d7bac38 100644 --- a/src/shared_func.h +++ b/src/shared_func.h @@ -1191,6 +1191,23 @@ static inline const char *long_to_comma_str(const int64_t n, char *buff) return long2str(n, buff, true); } +/** convert double to string + * parameters: + * d: the double number + * scale: number of decimal places (round off) + * buff: output buffer + * thousands_separator: if add thousands separator + * return: string buffer +*/ +const char *double2str(const double d, const int scale, + char *buff, const bool thousands_separator); + +static inline const char *double_to_comma_str(const double d, + const int scale, char *buff) +{ + return double2str(d, scale, buff, true); +} + const char *bytes_to_human_str(const int64_t bytes, char *buff); /** if the string starts with the needle string