num2str: fix precision loss bug when the fractional part is close to 1
authorgloit042 <gloit042@gmail.com>
Sun, 20 Dec 2020 16:35:21 +0000 (00:35 +0800)
committergloit042 <gloit042@gmail.com>
Mon, 21 Dec 2020 02:14:38 +0000 (10:14 +0800)
example:
The result of num2str(11999999999999, 4, 1, 0, N2S_NONE) should
be "12.0G", but current result is "11.0G".

Signed-off-by: Jiahao Li <gloit042@gmail.com>
lib/num2str.c

index 726f1c44159fd8a16379777411030b262eeb6cb1..423d97b2573986ac75fbf577358830b523fa2a83 100644 (file)
@@ -112,6 +112,9 @@ done:
        sprintf(tmp, "%.*f", (int)(maxlen - strlen(tmp) - 1),
                (double)modulo / (double)thousand);
 
+       if (tmp[0] == '1')
+               num++;
+
        if (asprintf(&buf, "%llu.%s%s%s", (unsigned long long) num, &tmp[2],
                     unitprefix[post_index], unitstr[units]) < 0)
                buf = NULL;