X-Git-Url: https://secure.softndesign.org/git/?a=blobdiff_plain;f=fdprintf.c;h=46f27acb8f6b7a05032a4bd5d1038f90011b6061;hb=5fe6254a8974dbe1fa199b5e3cc010af9bee87b3;hp=1bc1b1907a0de6f82d320a015d562131c39cb7ad;hpb=95834c7b69cecdc08bb2c7060d6b164513436274;p=calc.git diff --git a/fdprintf.c b/fdprintf.c index 1bc1b19..46f27ac 100644 --- a/fdprintf.c +++ b/fdprintf.c @@ -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, ...) @@ -64,7 +96,7 @@ int fdprintf (int fd, const char *fmt, ...) *str++ = c; } else { int t = 0; - char w = '0'; + char w = '0'; int i, sz = 0; void *p = NULL; @@ -80,6 +112,9 @@ int fdprintf (int fd, const char *fmt, ...) /* process format char */ switch (*fmt++) { + case '%': /* percent */ + *str++ = '%'; + break; case 'c': /* char */ c = (char) va_arg (ap, int); *str++ = c; @@ -97,30 +132,25 @@ int fdprintf (int fd, const char *fmt, ...) break; case 'f': /* float */ f = va_arg (ap, double); + if (f == 0) { + *str++ = '0'; + break; + } if (f < 0) { *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++; - } + if (sz == 0) sz = 6; + t = getexponant (&f, -sz); u = (int)f; str = itoa (str, u, 0); - d = (int)((f - u) * 1e6); + d = (int)((f - u) * tenpower (sz)); if (d > 0) { *str++ = '.'; - str = itoa (str, d, 6); + str = itoa (str, d, sz); + } + while (*(str - 1) == '0') { + str--; } if (t != 0) { *str++ = 'e';