AnsweredAssumed Answered

Issue printing negative floating point numbers - debug_printf

Question asked by Richard May on Mar 4, 2015
Latest reply on Jun 17, 2015 by Iva Susnova

Using KSDK 1.1.0 with no OS, I have been trying to use printf to output floating point numbers. I eventually settled on using PRINTF which is defined as debug_printf as printf did not output floating point numbers at all (even after following instructions in another thread (printf() with float values). debug_printf worked fine for positive numbers, but not for negative numbers. Junk characters were output instead.

Stepping through the revealed the problem to be in mkfloatnumstr which converts the float to a string.

The following code loops through the digits of the fractional part.


   for (i = 0; i < precision_width; i++)
      fb = fa / (int32_t)radix;
      c = (int32_t)(fa - (uint64_t)fb * (uint32_t)radix);
      if (c < 0)
         c = ~c + 1 + '0';
         c = c + '0';
      fa = fb;
      *nstrp++ = (char)c;

The problem is the calculation of c - as it is, with negative numbers, the sign of fb is lost, and so instead of c being the value of the least significant digit of fa, it becomes equal to fa. I believe the solution is to leave fb signed as follows.

      c = (int32_t)(fa - (int64_t)fb * (int32_t)radix);