473,395 Members | 1,341 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Float to String

YLD
Hi,

How could I copy a float to a string?
For example:

float number = 12.34;
char numberstring[5];
*introduce some magic code here*
resulting in numberstring == [ '1' | '2' | '.' | '3' | '4' | '\0' ]

Or soemthing similar... I thought it would be something very easy, but
after looking the FAQ and searching google I cant find an appropriate
way.

Thank you.

Nov 15 '05 #1
12 11984
YLD wrote on 10/09/05 :
How could I copy a float to a string?
Do you meant 'convert' ?
float number = 12.34;
char numberstring[5];
*introduce some magic code here*
resulting in numberstring == [ '1' | '2' | '.' | '3' | '4' | '\0' ]


sprintf() is your friend. Be sure than the destination array of char is
big enough.
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

I once asked an expert COBOL programmer, how to
declare local variables in COBOL, the reply was:
"what is a local variable?"
Nov 15 '05 #2
YLD
Thank you very much Emmanuel, the sprintf() hint was all that I needed
and of great help.

However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.
I post a sample code just in case anybody gets here looking for the
same information:

#include <stdio.h>

int main()
{
char *my_string;

asprintf (&my_string, "Being %d is cool, but being free is best of
all.", 4);
puts (my_string);

return 0;
}

Bye!

Nov 15 '05 #3
"YLD" <ru****@gmail.com> wrote:
Hi,

How could I copy a float to a string? <snip>

This is a faq, see section 13.1 (faq link in signature).

Short version: use sprintf
I thought it would be something very easy, [...]


It is. :)

However, I suggest you read section 12.21 of the faq about avoiding
buffer overruns when using sprintf.
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc frequent answers: http://benpfaff.org/writings/clc
Nov 15 '05 #4
YLD wrote on 10/09/05 :
However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.


Sounds good, unfortunately, it's not standard. However, a portable
implementation of this should be possible to achieve.

Note also that C99 supports snprintf().

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++
Nov 15 '05 #5
"YLD" <ru****@gmail.com> wrote:
Thank you very much Emmanuel, the sprintf() hint was all that I needed
and of great help.

However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.


Alas, asprintf is not standard C. If you happen to have a conforming
C99 implementation at hand, there's snprintf.

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc frequent answers: http://benpfaff.org/writings/clc
Nov 15 '05 #6
YLD wrote on 10/09/05 :
Thank you very much Emmanuel, the sprintf() hint was all that I needed
and of great help.

However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.
I post a sample code just in case anybody gets here looking for the
same information:

#include <stdio.h>

int main()
{
char *my_string;

asprintf (&my_string, "Being %d is cool, but being free is best of
all.", 4);
puts (my_string);

return 0;
}

Bye!


Of course, you want a test and a memory release:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

#if defined (linux)
#define F_NIL "/dev/null"
#elif defined (MSDOS) || defined (WIN32)
#define F_NIL "nul"
#else
#error not defined for this platform
#endif

int asprintf (char **pp_out, char const *fmt,...)
{
int n;
FILE *fp = fopen (F_NIL, "wb");

if (fp != NULL)
{
va_list va;
va_start (va, fmt);
{
n = vfprintf (fp, fmt, va);
fclose (fp);

{
char *s_out = malloc (n + 1);

if (s_out != NULL)
{
int ns = vsprintf (s_out, fmt, va);

assert (n == ns);

if (pp_out != NULL)
{
*pp_out = s_out;
}
}
else
{
n = -1;
}
}
}
va_end (va);
}
else
{
n = -1;
}
return n;
}
int main (void)
{
char *my_string;

asprintf (&my_string, "Being %d is cool, but being free is best of
all.", 4);

if (my_string != NULL)
{
puts (my_string);
free (my_string), my_string = NULL;
}

return 0;
}

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"There are 10 types of people in the world today;
those that understand binary, and those that dont."
Nov 15 '05 #7
(supersedes <mn***********************@YOURBRAnoos.fr>)

YLD wrote on 10/09/05 :
Thank you very much Emmanuel, the sprintf() hint was all that I needed
and of great help.

However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.
I post a sample code just in case anybody gets here looking for the
same information:

#include <stdio.h>

int main()
{
char *my_string;

asprintf (&my_string, "Being %d is cool, but being free is best of
all.", 4);
puts (my_string);

return 0;
}

Bye!


Of course, you want a test and a memory release:

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

#if defined (linux)
#define F_NIL "/dev/null"
#elif defined (MSDOS) || defined (WIN32)
#define F_NIL "nul"
#else
#error not defined for this platform
#endif

int asprintf (char **pp_out, char const *fmt,...)
{
int n;
FILE *fp = fopen (F_NIL, "wb");

if (fp != NULL)
{
va_list va;
va_start (va, fmt);
{
n = vfprintf (fp, fmt, va);
fclose (fp);

{
char *s_out = malloc (n + 1);

if (s_out != NULL)
{
int ns = vsprintf (s_out, fmt, va);

assert (n == ns);

if (pp_out != NULL)
{
*pp_out = s_out;
}
}
else
{
n = -1;
}
}
}
va_end (va);
}
else
{
n = -1;
}
return n;
}

int main (void)
{
char *my_string;

int n = asprintf (&my_string, "Being %d is cool, but being free is
best of all.", 4);

if (n > 0 && my_string != NULL)
{
puts (my_string);
free (my_string), my_string = NULL;
}

return 0;
}
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"
Nov 15 '05 #8
On 10 Sep 2005 09:17:15 -0700, "YLD" <ru****@gmail.com> wrote:
Thank you very much Emmanuel, the sprintf() hint was all that I needed
and of great help.

However, after searching about that I found out that asprintf() is much
safer, as you don't have to deal with how much space the destination
array needs. It is also very simple.


But is asprintf standard?
<<Remove the del for email>>
Nov 15 '05 #9
YLD
>This is a faq, see section 13.1 (faq link in signature).
Short version: use sprintf


I did look in the FAQ, but I guess I looked at the wrong section.
I didn't know asprintf wasn't standard.

Probably I will use sprintf and use a long array. Any way, if the
array is not long enough, what would be the worse that could happen?
Will I just miss precision? (I just need the first 4 significant
figures..)

Thanks again

Nov 15 '05 #10
YLD wrote on 10/09/05 :
I didn't know asprintf wasn't standard.
Google "man asprintf" "I'm lucky"

http://www.hmug.org/man/3/asprintf.php

HISTORY

The functions asprintf() and vasprintf() first appeared in the GNU
C
library. These were implemented by Peter Wemm <pe***@FreeBSD.org>
in
FreeBSD 2.2, but were later replaced with a different
implementation from
Todd C. Miller <To*********@courtesan.com> for OpenBSD 2.3.
Probably I will use sprintf and use a long array. Any way, if the
array is not long enough, what would be the worse that could happen?
Anything (Undefined behaviour). It's a serious bug.
Will I just miss precision? (I just need the first 4 significant
figures..)


'figures '? You meant 'digits', I guess...

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC
Nov 15 '05 #11
"YLD" <ru****@gmail.com> wrote:
This is a faq, see section 13.1 (faq link in signature).
Short version: use sprintf
I did look in the FAQ, but I guess I looked at the wrong section.
I didn't know asprintf wasn't standard.

Probably I will use sprintf and use a long array. Any way, if the
array is not long enough, what would be the worse that could happen?


Since you might invoke undefined behaviour by writing to memory you
don't own, absolutely anything can happen. Make sure the array is
large enough.
Will I just miss precision? (I just need the first 4 significant
figures..)


Specify the precision in the printf format string, e.g.:

sprintf( your_buf, "%.4g", your_double );

This will give you 4 significant digits, plus decimal point, plus
optional sign, plus eventually some characters for the exponent, plus
the terminating '\0'. It's difficult to tell beforehand, how many
characters the exponent will take, but at least 4 - two digits, sign
and 'e'. However, a generously oversized buffer will do. I hope I
won't get fried for making such a fuzzy assertion in c.l.c. :o)

Anyway, there's always one more option: write the number to a file
first, and the return value of fprintf will tell you the number of
characters written. Clumsy, but safe.

If you go for the %f format: IIRC there is a rule of thumb to estimate
the number of characters in the textual representation of a floating
point number in "ordinary" decimal notation. Alas, I'm unable to
reproduce it right now, I'm somewhat unorganized at the moment. I
wonder if anyone else could help me out?

Best Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc frequent answers: http://benpfaff.org/writings/clc
Nov 15 '05 #12
YLD wrote:
Hi,

How could I copy a float to a string?
For example:

float number = 12.34;
char numberstring[5];
*introduce some magic code here*
resulting in numberstring == [ '1' | '2' | '.' | '3' | '4' | '\0' ]


You can't fit 6 characters into an array of 5 chars.
My advice is for you to use snprintf() -- it's supported by
most C implementations, and if you find one where it isn't,
then it is easy to download some free source code for the function.

You mentioned you were going to use asprintf -- it seems to me that
any 'asprintf' implementation will need to refer to 'vsnprintf' anyway,
in order to work out how much memory to allocate.

Nov 15 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Bryan R. Meyer | last post by:
I am a relatively new C++ programmer and am attempting to write a function that takes a number of type float and adds commas to it in the appropriate places. In order to manipulate the number to...
3
by: Robb Gilmore | last post by:
Hello, We have a C#.NET app which is calling a Java webservice. We use the wsdl file exportted from the java webservice to create our web-reference in Visual Studio. We are able to create the...
6
by: karthi | last post by:
hi, I need user defined function that converts string to float in c. since the library function atof and strtod occupies large space in my processor memory I can't use it in my code. regards,...
15
by: thomas.mertes | last post by:
For a hash function I want to reinterpret the bits of a float expression as unsigned long. The normal cast (unsigned long) float_expression truncates the float to an (unsigned long) integer. ...
9
by: Python.LeoJay | last post by:
Dear all, i need to parse billions of numbers from a file into float numbers for further calculation. i'm not satisfied with the speed of atof() function on my machine(i'm using visual c++ 6)....
3
by: bofh1234 | last post by:
I am trying to write a function that returns a float. This is what the function should do: It takes the socket number and a variable name. The function looks up the variable in an array of...
6
by: trevor | last post by:
Incorrect values when using float.Parse(string) I have discovered a problem with float.Parse(string) not getting values exactly correct in some circumstances(CSV file source) but in very similar...
12
by: joestevens232 | last post by:
Okay, Im having some problems with my code. Im trying to use the <cstdlib> library and im trying to convert string data at each whitespace slot. I think if you see my code you'll get what im trying...
14
by: Jim Langston | last post by:
The output of the following program is: 1.#INF 1 But: 1.#INF 1.#INF was expected and desired. How can I read a value of infinity from a stream?
8
by: Ruben | last post by:
error: passing `const Weight' as `this' argument of `float Weight::wgt()' discards qualifiers seems to be some sort of standard error format that I'm not understanding. I have code that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.