View previous topic :: View next topic |
Author |
Message |
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
Formatting in printf |
Posted: Mon Mar 02, 2015 1:32 pm |
|
|
I'm using printf() to output some debug statements. But the float format does not seem to work correctly.
Code: |
float val = 100.974;
printf("%.2f\r\n", val);
|
Printout = "100.00"
I even tried the 'g' format, but no change. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Mar 02, 2015 2:05 pm |
|
|
What PIC and what compiler version ? Always post those. |
|
|
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
|
Posted: Mon Mar 02, 2015 2:30 pm |
|
|
Sorry. An 18F8722 with V5.042 PCWHD. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19546
|
|
Posted: Mon Mar 02, 2015 2:39 pm |
|
|
Try it with a minimum width. A lot of CCS versions do not like undefined widths.
So %3.2f which is the minimum that could hold the .xx part of the number. It'll expand as needed. |
|
|
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
|
Posted: Mon Mar 02, 2015 2:43 pm |
|
|
Didn't help. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Mar 02, 2015 2:44 pm |
|
|
Quote: | 18F8722 with V5.042 PCWHD. |
If I run a test program with that version in MPLAB simulator, I get
this output:
Test program:
Code: |
#include <18F8722.h>
#fuses INTRC_IO, NOWDT
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
//==============================
void main()
{
float val = 100.974;
printf("%.2f\r\n", val);
while(TRUE);
} |
|
|
|
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
|
Posted: Mon Mar 02, 2015 2:53 pm |
|
|
That worked. |
|
|
SeeCwriter
Joined: 18 Nov 2013 Posts: 160
|
|
Posted: Mon Mar 02, 2015 3:11 pm |
|
|
But back to my program, even doing the following doesn't change the output.
Code: |
char str[8];
sprint( str, "%3.2f", val );
printf("My val: %s\r\n", str );
|
Output = 100.00
I can break just before printf() and mouse over 'val' and it shows the correct value of 100.974. |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Mar 02, 2015 4:10 pm |
|
|
I don't know anything about mousing over. I never do that.
If I run the test program below in MPLAB Simulator (MPLAB vs. 8.92),
I get the following output displayed in the Sim UART1 window:
Test program:
Code: |
#include <18F8722.h>
#fuses INTRC_IO, NOWDT
#use delay(clock=4M)
#use rs232(baud=9600, UART1, ERRORS)
//==============================
void main()
{
float val = 100.974;
char str[8];
sprintf( str, "%3.2f", val );
printf("My val: %s\r\n", str );
while(TRUE);
} |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19546
|
|
Posted: Tue Mar 03, 2015 8:31 am |
|
|
I'd be suspicious of a simulator problem. Except for some very old V4 compilers which give problems without a field width, everything I've tried works OK.... |
|
|
|