Image

Imagevolatilevoid wrote in Imagecpp

float woes

INCOMING CODE! :)
char *ftoa (double f, char *s)
{
  unsigned int i = (f < 0.0) ? -f : f;
  unsigned int j = i, decpos = 0;
  double t = (f < 0.0) ? -f : f;

  while (j < t)
  {
    t *= 10;
    decpos++;
    j = t;
  }

  j -= (i * pow (10, decpos));

  if (f < 0.0)
    sprintf (s, "-%i.%i", i, j);
  else
    sprintf (s, "%i.%i", i, j);

  return s;
}


The problem: I forgot that division of floats/doubles is actually imprecise by nature. If you pass in a double that's too large (too many digits after the decimal point), the while loop will turn into an infinite loop because of the way multiplication / division works with floats.

I thought my implementation was clever and then realized why noone ever wrote a decent ftoa to begin with. :(

Alas.
Michael