11 years, 3 months ago.

float (or integer) to char (or string) conversion

Can anyone help me with probably a very simple question?

I need to convert an integer (numeric) value to character (string) value to use the 4dsystems draw text function in my code below. The mbed printf works fine but half the speed compared with drawText when sending information to my Oled display.

Thank you

Paul



    float temp2 = tmp[1];

    oled.printf("%03.f'c",temp2); // don't want to use this

    oled.drawText(1,1,(OLED_FONT8X12),temp2,oled.toRGB(255,255,255)); // I want to use this


// this is the library function I'm using

void OLED32028P1T::drawText(int column, int row, int font_size, char *mytext, int color)
{
    s.putc(OLED_TEXT);
    // Adjust to center of the screen (26 Columns at font size 0)
    //int newCol = 13 - (strlen(mytext)/2);
    //printByte(newCol); // column
    s.putc(column); // column
    s.putc(row); // row
    s.putc(font_size); // font size (0 = 5x7 font, 1 = 8x8 font, 2 = 8x12 font)
    s.putc(color >> 8);      // MSB
    s.putc(color & 0xFF);    // LSB
    for (int i = 0;  i < strlen(mytext); i++) {
        s.putc(mytext[i]); // character to write
    }
    s.putc(0x00);   // string terminator (always 0x00)
    getResponse();
}

2 Answers

11 years, 3 months ago.

Hi Paul,

Let's say that you want to convert an "int" into a "char *". You can use sprintf:

char buf[10];
int a = 5;
sprintf(buf, "%d", a);

Take a look at the sprintf doc.

Cheers, Sam

Accepted Answer
Paul Staron
poster
11 years, 3 months ago.

Thanks Sam. That worked fine for integer's but I need to convert a float.

I can use this I found on a forum:

char str[100];
float adc_read = 678.0123;

int d1 = adc_read;            // Get the integer part (678).
float f2 = adc_read - d1;     // Get fractional part (678.0123 - 678 = 0.0123).
int d2 = trunc(f2 * 10000);   // Turn into integer (123).
//int d2 = (int)(f2 * 10000); // Or this one: Turn into integer.

// Print as parts, note that you need 0-padding for fractional bit.
// Since d1 is 678 and d2 is 123, you get "678.0123".
sprintf (str, "adc_read = %d.%04d\n", d1, d2);

But this is quite messy and and processor time consuming. I was hoping there would be more simple function in C++ or on the Mbed compiler that would do this.

Regards.

Paul

If you got a float, simply replace %d by %f in Samuel's example.

posted by Erik - 19 Jan 2013

Thank you Eric I will give that a try

posted by Paul Staron 02 Feb 2013