summaryrefslogtreecommitdiff
path: root/lib/num2str.c
diff options
context:
space:
mode:
authorJens Axboe <jaxboe@fusionio.com>2010-09-16 14:56:23 +0200
committerJens Axboe <jaxboe@fusionio.com>2010-09-16 14:56:23 +0200
commit05463816cb6944649ac152283a9d02629ff91c0d (patch)
tree0d4b81296f6ae26922a2aa3414bbb288c1893703 /lib/num2str.c
parent1ec3d69b0ed8cc7a3eba0192685034d5442989e4 (diff)
downloadfio-05463816cb6944649ac152283a9d02629ff91c0d.tar.gz
num2str fixes
Signed-off-by: Jens Axboe <jaxboe@fusionio.com>
Diffstat (limited to 'lib/num2str.c')
-rw-r--r--lib/num2str.c22
1 files changed, 16 insertions, 6 deletions
diff --git a/lib/num2str.c b/lib/num2str.c
index e114cdf8..559cbeb5 100644
--- a/lib/num2str.c
+++ b/lib/num2str.c
@@ -10,8 +10,8 @@ char *num2str(unsigned long num, int maxlen, int base, int pow2)
char postfix[] = { ' ', 'K', 'M', 'G', 'P', 'E' };
unsigned int thousand[] = { 1000, 1024 };
unsigned int modulo, decimals;
- int post_index;
- char tmp[32], fmt[8];
+ int post_index, carry = 0;
+ char tmp[32];
char *buf;
buf = malloc(128);
@@ -27,6 +27,7 @@ char *num2str(unsigned long num, int maxlen, int base, int pow2)
modulo = num % thousand[!!pow2];
num /= thousand[!!pow2];
+ carry = modulo >= thousand[!!pow2] / 2;
post_index++;
}
@@ -38,11 +39,20 @@ done:
sprintf(tmp, "%lu", num);
decimals = maxlen - strlen(tmp);
- if (decimals <= 1)
+ if (decimals <= 1) {
+ if (carry)
+ num++;
goto done;
+ }
+
+ do {
+ sprintf(tmp, "%u", modulo);
+ if (strlen(tmp) <= decimals - 1)
+ break;
+
+ modulo = (modulo + 9) / 10;
+ } while (1);
- sprintf(fmt, "%%.%uu", decimals - 1);
- sprintf(tmp, fmt, modulo);
- sprintf(buf, "%lu.%s%c", num, tmp, postfix[post_index]);
+ sprintf(buf, "%lu.%u%c", num, modulo, postfix[post_index]);
return buf;
}