Solved

# Convert Float to Ascii Char string

Posted on 2003-03-26
Medium Priority
7,782 Views
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
Question by:Terrance
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 5
• 5
• 3
• +5

LVL 30

Expert Comment

ID: 8209327
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

LVL 1

Expert Comment

ID: 8209369
#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

LVL 30

Expert Comment

ID: 8209394
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

LVL 3

Expert Comment

ID: 8210156
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

LVL 30

Expert Comment

ID: 8210187
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

LVL 3

Expert Comment

ID: 8210300
"%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

LVL 30

Expert Comment

ID: 8210328
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

LVL 3

Expert Comment

ID: 8210391
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

LVL 30

Expert Comment

ID: 8210464
>> 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

LVL 3

Expert Comment

ID: 8210525
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

LVL 2

Expert Comment

ID: 8211328
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

Expert Comment

ID: 8211853
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

LVL 2

Expert Comment

ID: 8211915
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

LVL 3

Expert Comment

ID: 8212191
>>>> 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 Comment

ID: 8214781
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

LVL 2

Accepted Solution

honey_hamster earned 150 total points
ID: 8214997
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

LVL 1

Expert Comment

ID: 8215933
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 Comment

ID: 8216129
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

LVL 1

Expert Comment

ID: 8224043
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 Comment

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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn hoâ€¦
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and infâ€¦
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
###### Suggested Courses
Course of the Month8 days, 14 hours left to enroll