/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>

static int pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };

void i2s(int v, int w, char *buf, char fill)
{
    int i,tmp;
    char *p = buf + w;
    *p = '\0';
    p--;
    tmp = v;
    for(i = 0; i < w; i++)
    {
        if(tmp > 0)
        {
            *p = '0' + tmp % 10;
            tmp /= 10;
        }
        else
        {
            *p = fill;
        }
        p--;
    }
}

void f2s(float x, int w, int nd, char *buf)
{
    int tmp;
    tmp = (int)x;
    i2s(tmp, w - nd - 1, buf, ' ');
    buf[w - nd - 1] = '.';
    i2s((int)((x - tmp) * pow10[nd]), nd, buf + w - nd, '0');
}

#define MAX(a,b) (a>b?a:b)

void f2s_free(float x, char *buf)
{
    int n = 1;
    while(x >= pow10[n]) n++;
    f2s(x, MAX(8,n+2), MAX(1,7-n), buf);
}

int main()
{
    char buf[16];
    float x = 123.456;
    printf("%9.4f\n", x);
    f2s(x, 9, 4, buf);
    printf("%s\n", buf);
    printf("%f\n", x);
    f2s_free(x, buf);
    printf("%s\n", buf);
    return 0;
}
