clean printf for %f
authorLaurent Mazet <mazet@softndesign.org>
Wed, 28 Dec 2022 08:31:03 +0000 (09:31 +0100)
committerLaurent Mazet <mazet@softndesign.org>
Wed, 28 Dec 2022 08:31:03 +0000 (09:31 +0100)
fdprintf.c

index 6c06e038de3c897ae20b77c5a7d01221ed26ce5d..76722fc508851be20d29be71f906a06b6f3e276b 100644 (file)
@@ -43,6 +43,38 @@ char *itoa (char *str, unsigned u, unsigned int sz)
     return s;
 }
 
+double tenpower(int n)
+{
+    double t = 1.0;
+    int i;
+    for (i = 0; i < n; i++) {
+        t *= 10;
+    }
+    for (i = 0; i > n; i--) {
+        t /= 10;
+    }
+    return t;
+}
+
+int getexponant (double *f, int maxexp)
+{
+    int exp = 0;
+    while (*f > 10) {
+        *f /= 10;
+        exp++;
+    }
+    while (*f < 1) {
+        *f *= 10;
+        exp--;
+    }
+    *f += tenpower (maxexp - 1);
+    if (*f >= 10) {
+        *f /= 10;
+        exp++;
+    }
+
+    return exp;
+}
 /* simple fprintf function */
 
 int fdprintf (int fd, const char *fmt, ...)
@@ -105,27 +137,17 @@ int fdprintf (int fd, const char *fmt, ...)
                     *str++ = '-';
                     f = -f;
                 }
-                t = 0;
-                while (f > 10) {
-                    f /= 10;
-                    t++;
-                }
-                while (f < 1) {
-                    f *= 10;
-                    t--;
-                }
-                f += 1e-7;
-                if (f >= 10) {
-                    f /= 10;
-                    t++;
-                }
+                t = getexponant (&f, -6);
                 u = (int)f;
                 str = itoa (str, u, 0);
-                d = (int)((f - u) * 1e6);
+                d = (int)((f - u) * tenpower (6));
                 if (d > 0) {
                     *str++ = '.';
                     str = itoa (str, d, 6);
                 }
+                while (*(str - 1) == '0') {
+                    str--;
+                }
                 if (t != 0) {
                     *str++ = 'e';
                     if (t < 0) {