Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 8098

# Convert Float to Ascii Char string

Guys, How to convert Float to Ascii Char string. Please don't say use ftoa() or gcvt() because my complier cannot support all the libreay function. If any one who write the C function please sen dit to me

regards
Terrance
0
Terrance
• 5
• 5
• 3
• +5
1 Solution

Associate Director - Product EngineeringCommented:
I will give you a hint as to how to convert an integer to a string using the moduko-div method....

void convert ( int val, char str[] )
{
int digit, count = 0 ;

str[0] = '\0' ;

while ( val != 0 )
{
digit = val % 10 ;
str[count++] = (char) digit + '0' ;
val = val / 10 ;

} // end while

str[count] = '\0' ;

} // end of convert ()

Hope you can try for a floating-point number....

Mayank.
0

Commented:
#include <stdlib.h>
#include <stdio.h>

void main()
{

char *buf;

double value = 3.156;
int count = 3; //number of digits after decimal point
int dec; //place of the decimal point
int sign; //sign of the number

//first method
buf = _fcvt( value, count, &dec, &sign );
if (sign == 0)
{
printf("-%.*s.%.*s",count,buf,strlen(buf)-dec,&buf[dec-1]);
}
else
{
printf("-%.*s.%.*s",count,buf,strlen(buf)-dec,&buf[dec-1]);
}

//second method
buf = new char[20];
sprintf(buf,"%f",value);
printf("%s",buf);
delete buf;

}
0

Associate Director - Product EngineeringCommented:
oferh ,

>> //number of digits after decimal point

Supposing that the number is a user-input and you don't know the number of digits after the decimal point before-hand. The user can enter something like 3.000011?

Mayank.
0

Commented:
Use sprintf, a function that is part of the C Standard.  It is just like printf, but it writes the data to a string.

char theString[128];
double number = 3.141592;

sprintf(theString, "%f", number);

Hope this helps,

Marc
0

Associate Director - Product EngineeringCommented:
Slight correction to that: use "%lf" instead of "%f" (for 'double') in the sprintf (). Might cause trouble in some platforms/ versions.... I can never stop to explain the unexpected loss in precision while dealing with floating-point values.

Mayank.
0

Commented:
"%f" is the correct conversion specifier for double (or float).  By default, the "%f" will give you a precision of 6, but you can override this yourself.  "%lf" should be used for 'long double'.

Marc
0

Associate Director - Product EngineeringCommented:
Don't think so, pal.... at least on my system, it gives 3.140000 with "%f" and 3.141592 with "%lf". I'm using Turbo C++ 3.0 on Windows 2000.

Mayank.
0

Commented:
I mean no offense, but Turbo C++ 3.0 (which is several years old), is not following the Standard if this is the result you are getting.

double number;

printf("%.6f", number);

should be equivalent to

printf("%f", number);

The C Standard specifically sets the default precision to 6 for the "%f" conversion specifier.

Marc
0

Associate Director - Product EngineeringCommented:
>> which is several years old

I agree.

Actually, I was just talking about being on the safe side.... I hope you wouldn't mind visiting this:

http://www.experts-exchange.com/Programming/Programming_Languages/C/Q_20548837.html

Cheers,

Mayank.
0

Commented:
I read the question that you linked to, but I don't think that is the issue here.  I am familier with how the floating point representation works (http://www.experts-exchange.com/Databases/Q_10129995.html), but when dealing with printf, "%f" (if the compiler is written correctly) is to be used for both float and double.

From the C Faq:

12.9:   Someone told me it was wrong to use %lf with printf().  How can
printf() use %f for type double, if scanf() requires %lf?

A:      It's true that printf's %f specifier works with both float and
double arguments.  Due to the "default argument promotions"
(which apply in variable-length argument lists such as
printf's, whether or not prototypes are in scope), values of
type float are promoted to double, and printf() therefore sees
only doubles.  (printf() does accept %Lf, for long double.)

References: K&R1 Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-50; K&R2
Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-59; ISO Sec. 7.9.6.1,
Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64, Sec. 15.11 pp. 366-78;
CT&P Sec. A.1 pp. 121-33.

So, from printf's point of view, it does not matter if the variable you are printing is float or double, "%f" should suffice.

Marc
0

Commented:
Here's some 'C' code that might be close to what you want.

#include <stdio.h>

#define LARGEST_ONE  10000000000
#define SMALLEST_ONE 0.0001

int main( void )
{
double val = 8765.432;
double temp = LARGEST_ONE;
char  value_needed = 0;
char  digit;
char  buffer[16];
char  *buffer_ptr = buffer;

temp = LARGEST_ONE;

/* Do the digits to the left of the decimal */
while( val >= 1 )
{
digit = 0;

while( val > temp )
{
val -= temp;
digit++;
}

if( !value_needed && digit )
{
value_needed = 1;
}

if( value_needed )
{
if( digit > 9 )
{
*buffer_ptr = '?';
}
else
{
*buffer_ptr = '0' + digit;
}

buffer_ptr++;
}

temp = temp / 10;
}

if( !value_needed )
{
*buffer_ptr++ = '0';
}

*buffer_ptr++ = '.';

while( val > SMALLEST_ONE )
{
digit = 0;

while( val > temp )
{
val -= temp;
digit++;
}

*buffer_ptr++ = '0' + digit;

temp = temp / 10;
}

puts( buffer );

return( 0 );
}
0

Commented:
Only use the function sprintf (this is part of the standard ANSI)

#include <stdio.h>

length = sprintf(s,fmt,arg1,arg2,...);

int length;                    /* number of characters generated */
char *s;                    /* pointer to a character string */
const char *fmt;            /* format string */
type argx;                      /* arguments */

This function produces an output stream of ASCII characters and
sends the output to the storage area whose address is given by the
argument s.  Make sure that this area is large enough to hold the
maximum number of characters that might be generated. The sprintf
function also generates a NULL byte to terminate the stored
string.
0

Commented:
If your compiler doesn't support ftoa(), then I'm guessing you're in an embedded environment.  If it's a small embedded environment, then you might well want to avoid using sprintf() due to its size.
0

Commented:
>>>> If your compiler doesn't support ftoa(), then I'm guessing you're in an embedded environment

This is not necessarily true.  gcc, the GNU compiler, does not support 'ftoa' because it is not part of Standard C or POSIX, and I use gcc on Linux in a non-embedded environment.

Marc
0

Author Commented:
Hi Guys,
It is true that i am in Embedded enviroment. So the library function is not the solution. Mayankeagh you suggest the division method which is true if you are dealing with undigned char or int but this is floating point. So keep in mind the data store insight 4 byte in differnt order, for example in

Char 15     00001111
int  15     00000000  00001111
float 15    00000000  0000001 00001001 00000001

you cannot convert in just simple way. I am expecting some function just exacttly same as ftoa() or gcvt(), if any of you earlier please pass it to me. To reduce my time to implement

0

Commented:
Terrance,

I already posted the following code, but here it is in the format of a subroutine.

#define LARGEST_ONE  10000000000
#define SMALLEST_ONE 0.0001

void ftoa( float val, char *buffer_ptr )
{
float temp = LARGEST_ONE;
char  value_needed = 0;
char  digit;

/* Do the digits to the left of the decimal */
while( val >= 1 )
{
digit = 0;

while( val > temp )
{
val -= temp;
digit++;
}

if( !value_needed && digit )
{
value_needed = 1;
}

if( value_needed )
{
if( digit > 9 )
{
*buffer_ptr = '?';
}
else
{
*buffer_ptr = '0' + digit;
}

buffer_ptr++;
}

temp = temp / 10;
}

if( !value_needed )
{
*buffer_ptr++ = '0';
}

*buffer_ptr++ = '.';

while( val > SMALLEST_ONE )
{
digit = 0;

while( val > temp )
{
val -= temp;
digit++;
}

*buffer_ptr++ = '0' + digit;

temp = temp / 10;
}

*buffer_ptr = '\0';
}
0

Commented:
I would like to take a shot at solving this one. Can you tell me a) which processor your program will run on and b)what kind of float you are using? What I have in mind dumping the native floating point number format into a decimal format. Usually they are 4 or 8 bytes, so I need to lookup the right one. If you need portability, then honey_hamster's answer looks good (but I didn't try to compile it).
0

Author Commented:
Hi Honey_master and cjs

First of all this is simple 8051 Core ASIC. usinf keil complier. Honey i did  not try ur code i will be trying today
0

Commented:
Hi there,
I have got a simple idea which u can use ... dunno how effective will be that..
just create a temp file and write the float number (using %f) in that file and then read it back as a string (using  %s). It will work ... is not the idea simple.. ha ha .

regards
ramesh
0

Author Commented:
Thanks honey master, There is minor modifiaction i did to achived the correct answer. You are almost there
0

## Featured Post

• 5
• 5
• 3
• +5
Tackle projects and never again get stuck behind a technical roadblock.