HOME

PROJECTS

TUTORIALS

C FUNCTIONS

PROGRAMS

PRODUCTS

VIDEOS

COMPANY

SPANISH

                 
How to convert a float variable to a string in C18 using the sprintf or printf  functions.

 

 

 

 

Description:

In the C18 compiler, the libraries that handle the printf or sprintf functions do not support floating point format. The reason: the cost to include floating point support in this libraries, would double its code memory usage in the microcontroller.

However, for the C18 programmer, the solution to this limitation of the compiler is fairly simple: convert first the floating point variable to two integers, managing fixed point. The first value is the whole part, and the second the fractional part.

 

You can download here Microchip's document which explains in more detail the above:

HOW-TO-CONVERT-A-FLOAT-TO-ASCII-IN-C18.pdf

COMPLETE EXAMPLE:

Here is an example of this conversion: in the segment of program shown below, the variable 'a' which was previously defined as floating point, is converted to its whole part and a decimal part (both variables must be previously declared as integers).

Finally, in the sprintf function, the variables whole and decimal are handled with fixed point and converted to a string (named array), to later display in the LCD of the system.

Please note how the decimal part can be set to 1 digit (multiplying by 10), 2 digits (multiplying by 100) and so on.

float a;
int whole,decimal;
char array[10];
void main( )
{
init_bolt( );
InitLCD( );
ClearScreen( );
a=3.0048;
whole=a; //whole part
decimal=(a-whole)*10000; //decimal part
sprintf(array,"%3d.%04d",whole,decimal); //Convert to string
PrintString(array); //show in LCD
for(;;);
}

The complete example source program for the Bolt 18F2550 system, which reads DS18B20 temperature sensor and displays centigrades and farenheit on the LCD, is as follows:

C18-BOLT-DS18B20.c

Similar method should be used with the printf( ) function.