TonyP
TonyP

Reputation: 5873

How do I call this function c

First apologize for asking this dumb question:

How to call this function in c (GNU C)

char *ftoa(float f, char *buf, int places)

Upvotes: 0

Views: 540

Answers (3)

rktcool
rktcool

Reputation: 356

I think the GNU implementation of C doesn't have a predefined function ftoa()

You could use sprintf() as follows :

float f;
char *a = (char *)malloc(10*sizeof(char)); //assuming you need 10 characters to store f
sprintf(a, "%f", f);

If you want to have only a specific number of decimal places, you could use "%0.2f" (for two digits after decimal point) etc. instead of "%f"

sprintf() could come in handy instead of the itoa() function. For example:

char *a = (char *)malloc(10*sizeof(char);
int x = 10;
float f = 12.4;
sprintf(a, "%d", x);  //=itoa() function
sprintf(a, "%f", f);

Good luck!

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129484

I prefer:

#define DECIMALS 10
char result[DECIMALS+1];
ftoa(SOME_FLOAT_VALUE, result, decimal_places);

I too would suggest using sprintf for greater flexibility.

The reason I prefer static allocation is that this will take up less space, it is automatically de-allocated when you leave the function [if that's not what you want, obviously, you may need malloc, but on stack allocation for small variabls, and 11 bytes is small!, should be the preferred way. I see WAY too much code with meaningless allocations - it wastest memory, and adds extra code. [The overhead of allocating 11 bytes from the heap is probably more than 11 bytes, as it will have to be rounded to 12 bytes, then a 'header' to account for the allocation, which in many systems is 16 or 32 bytes, in some cases 12 bytes]

Upvotes: 0

Nikos C.
Nikos C.

Reputation: 51900

This is how you call it:

int decimal_places = 10;
char* result = malloc(decimal_places + 1);
ftoa(SOME_FLOAT_VALUE, result, decimal_places);

The function returns its buf argument. As always, don't forget to free() the result string when you're done with it.

Upvotes: 3

Related Questions