Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
TeMa_1467596
Level 5
Level 5
5 sign-ins 5 likes given First like received

I couldn't make ftoa work and I wanted to control the display format and rounding - then I came across this code snippet and adapted it but it's still not quite what I need.

Can someone please help me tweak it to add a significant digit parameter so that I can specify how many digits after the decimal point?

Here is the routine

//*****************************************************************************

// TM convert float to string

// tested and working on PSoC6

//*****************************************************************************

void tmFtoStr(char* p, float x)

{

    int n,i=0,k=0;

    n=(int)x;

    while(n>0)

    {

        x/=10;

        n=(int)x;

        i++;

    }

    *(p+i) = '.';

    x *= 10;

    n = (int)x;

    x = x-n;

    while((n>0)||(i>k))

    {

        if(k == i)

            k++;

        *(p+k)='0'+n;

        x *= 10;

        n = (int)x;

        x = x-n;

        k++;

    }

    /* Null-terminated string */

    *(p+k) = '\0';

}

I call it like this

int main(void)

{

    float flt1;

    char myString[20]={};

    flt1 = 3.142;

    tmFtoStr(myString, flt1);

    printf("%s\n", myString);

.......

}

but the print out from the above is like this...

3.141999721527

I think I know what to do but I am scared that I'll break it -  I want to add a sigDig parameter so I call it like this...

tmFtoStr(myString, flt1, 3);

and get 3.142 - ideally doing rounding if possible.  Any help would be appreciated.

Also, is the problem above because of the inability of floats to store precisely?

Ted

0 Likes
1 Solution
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

You may use sprintf() function to convert any variable to string.

Requires: Set the heap size to 0x0200 (System view) and allow newlib nano float formatting (Build settings)

Usually double is more precise than float

Bob

View solution in original post

0 Likes
5 Replies