Dumbo
Dumbo

Reputation: 14112

Function with string as return type

I wrote a function to print a float value neatly. At the moment it directly outputs it on screen, but somewhere else in my code I need to store the result of this function in a variable as string (or char[]). Any suggestion please?

void printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    float f = toBePrinted;

    if (f<0)
    {
        c = '-';
        f = -f;
    }
    else
    {
        c = ' ';
    }

    // integer portion.
    fi = (uint32_t) f;

    // decimal portion...get index for up to 3 decimal places.
    f = f - ((float) fi);
    f0 = f*10;   f0 %= 10;
    f1 = f*100;  f1 %= 10;
    f2 = f*1000; f2 %= 10;
    if(c == '-')
        printf("%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        printf("%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

What should be return type of this function? I want at the end to do something like:

char[32] buffer;
buffer = printfFloat(_myFloat);

Upvotes: 3

Views: 938

Answers (3)

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

What should be return type of this function?

C does not have a String datatype, so you would have to pass the address of the buffer as a parameter:

char[32] buffer;
printfFloat(_myFloat, buffer);

Your function would become:

void printfFloat(float toBePrinted, char *buffer)
{
   ///rest of code

   if(c == '-')
    sprintf(buffer, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
   else
     sprintf(buffer, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

Upvotes: 3

nouney
nouney

Reputation: 4411

Take a look at asprintf, it will allocate a buffer and fill it for you.

char *printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    char *ret = NULL;
    float f = toBePrinted;

    if (f<0)
    {
        c = '-';
        f = -f;
    }
    else
    {
        c = ' ';
    }

    // integer portion.
    fi = (uint32_t) f;

    // decimal portion...get index for up to 3 decimal places.
    f = f - ((float) fi);
    f0 = f*10;   f0 %= 10;
    f1 = f*100;  f1 %= 10;
    f2 = f*1000; f2 %= 10;
    if(c == '-')
        asprintf(&ret, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        asprintf(&ret, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    return ret;
}

In the main:

#include <stdio.h>
int main()
{
   char *ret = printfFloat(42.42);
   puts(ret); // print ret
   free(ret);
   return 0;
}

Upvotes: 0

Anickyan
Anickyan

Reputation: 414

You can use the sprintf function.

char buffer[32];
sprintf(buffer, "%f", your_float);

Upvotes: -1

Related Questions