miketwo
Joined: 04 Aug 2010 Posts: 24
|
Workaround for printing floats |
Posted: Fri Aug 06, 2010 4:55 pm |
|
|
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. |
|