0

I am writing a function that will be passed a float in the form of a void pointer. What I am attempting to do, is convert that float into a string equivalent so that I might save that binary data in memory. For example, the call to my function is as follows:

void * f(void * data);

If a user passes me

float value = 3.14;

I would like to convert it into a string as shown below:

"3.14"

The approach that I think I should use, would be to first determine the number of values within the float: 3.14 = four values. I would then have to loop through each value and convert it to a character.

A couple problems I am having, is 1: I'm not sure if it is even possible to determine the number of values associated with a given float. 2: How would I convert each value into its string equivalent?

I came across itoa and sprintf. However, itoa isn't part of the standard C libary, and I am unsure as to whether or not sprintf will do as I desire.

Charles
  • 50,943
  • 13
  • 104
  • 142
kubiej21
  • 700
  • 4
  • 14
  • 29
  • 2
    sprintf(str, "%4.2f", float) – Eddy_Em Feb 04 '13 at 06:39
  • 1
    You probably want `sprintf`. You can't (generally) figure out a number of digits -- something that's passed as (for example) `1.2` will end up as something on the order of `1.99999999999999` (out to the precision of the type -- but binary floating point can't represent `0.2` precisely. – Jerry Coffin Feb 04 '13 at 06:40

1 Answers1

3

Most systems (in particular POSIX ones) have snprintf (and strdup) so you could code

 char buf[48];
 snprintf (buf, sizeof(buf), "%f", x);

if you want to return that string, strdup it (then you'll need to free the result of strdup later).

PS: sprintf is more dangerous than snprintf because it could overflow the buffer

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    and remember to free the buffer(from `strdup()`) later. – जलजनक Feb 04 '13 at 06:43
  • Would it be safe to assume that the float could never be larger than the buffer if the buffer is allocated with 48 bytes? – kubiej21 Feb 04 '13 at 06:43
  • A `float` is 4 bytes on most PCs; a `double` is 8 bytes; the result of `snprintf` then `strdup` may have more than a dozen of bytes (and `malloc`-ed memory like the result of `strdup` often have some overhead). – Basile Starynkevitch Feb 04 '13 at 07:21
  • `snprintf` is part of the C standard since 1999. – Jens Gustedt Feb 04 '13 at 08:07
  • @BasileStarynkevitch I don't think the size of the `float` has much of a connection to the size of its string representation. [This answer](http://stackoverflow.com/questions/1701055/what-is-the-maximum-length-in-chars-needed-to-represent-any-double-value) computes the max # of chars for a `double` to be 1078. Which is a lot. – unwind Feb 04 '13 at 09:11
  • I do know that the size of a `float` is not much related to the size of its string representation. – Basile Starynkevitch Feb 04 '13 at 18:10