CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug Reports on this forum. Send them to support@ccsinfo.com

Workaround for printing floats

 
Post new topic   Reply to topic    CCS Forum Index -> Code Library
View previous topic :: View next topic  
Author Message
miketwo



Joined: 04 Aug 2010
Posts: 24

View user's profile Send private message

Workaround for printing floats
PostPosted: Fri Aug 06, 2010 4:55 pm     Reply with quote

Hello everyone.

In my version of the compiler (PCD 4.109) and IDE (MPLAB 8.53.00.00), printing floats seems to be a little buggy. Every once in a while it'll reset with a trap conflict when I try to sprintf() with a %f.

So here's some workaround code:

Code:

// Custom Float Printing because sprintf %f crashes often.
void printFloat(char *string, float64 num, int precision) {
   // 8 bit enough for v
   int e = 0, v;
   int i;

   // Position in the string buffer to write to
   if (num < 0) {
      *string++ = '-';
      num = -num;
   }

   // Find E value
   while (num >= 10) {
      e++; num = num/10;
   }
   while (num < 1 && num > 0) {
      e--; num = num*10;
   }

   // Now num should be in [1, 10)
   v = (int) num;
   num = num - v;
   *string++ = v+'0';
   *string++ = '.';

   // Digits after the dot
   for (i=0; i<precision; i++) {
      num = num * 10;
      v = (int) num;
      *string++ = v +'0';
      num = num-v;
   }

   sprintf(string, "e%d", e);
}


The code is written for float64's, but you can use it for regular float32s as well. I recommend sticking with ~6 for the precision.

Cheers.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> Code Library All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group