Home arrow Support arrow Forums

Luminary Micro Forums

magnuslundinse

Gold Boarder
Click here to see the profile of this user

2006/12/05 15:37

ftoa

Code:

  void ftoa(float f,char *buf) {     int pos=0,ix,dp,num;     if (f<0)     {         buf[pos++]='-';         = -f;     }     dp=0;     while (f>=10.0)      {         f=f/10.0;         dp++;     }      for (ix=1;ix<8;ix++)     {             num f;             f=f-num;             if (num>9)                 buf[pos++]='#';             else                 buf[pos++]='0'+num;             if (dp==0buf[pos++]='.';             f=f*10.0;             dp--;     } }




This works and is very memory efficient, and seems to be correct up to 7 significant digits.

Have fun,
Magnus

login or register to reply

kode4fun

Senior Boarder
Click here to see the profile of this user

2006/12/30 15:33

Re:ftoa

Magnus,

Thanks for sharing this. It's a very good piece!
I tried it on my PC, it works as described. Even though I haven't tried it on an actual MCU, but I think it will work.

Here is my one cent comment:)
1. It would be nice to add control allowing user to select how many digits to output. This can be done by adding the third parameter.
2. Though this is minor, if float f has a large integral part and exceeds 7 digits, the displayed result is not correct. I modified the for loop condition to for (ix = 1; ix < 8 || dp >= 0; ix++) to fix it. Of course, the size of buf must be big enough.
3. If other users need more precision, replacing float with double can help. However, bigger code size and slower execution may result.

cheers,
jc

login or register to reply

ringram2077

Expert Boarder
Click here to see the profile of this user

2007/01/01 20:58

Re:ftoa

I tried it on the LM3S811 EVB and it works perfectly. Thank you for posting the code. These snippits are really helpful to newbies like me :-}

Richard

login or register to reply