Operating System - HP-UX
1751967 Members
4668 Online
108783 Solutions
New Discussion юеВ

float to string conversion problem

 
LEJARRE Patrick
Advisor

float to string conversion problem

The following source eliminates all sigificant decimals. Can someone help me to fix this issue ?

#include
int main()
{
float num = 10.55164516854;
char s[80];
sprintf(s, "%10.10f", num); /* write the double to a string */
printf("Here is the result: %s\n", s);
return 0;
}
Result: Here is the result: 10.0000000000
but should be 10.5516451685

Many thanks in advance.
5 REPLIES 5
benoit Bruckert
Honored Contributor

Re: float to string conversion problem

Hello Patrick,
What is the compiler ?
I treid this program and it worked fine with cc (the K&R from HP , not the Ansi) and with gcc.
Any options with cc ? What version of HPUX ? of cc/gcc ?

hope that help
Benoit
Une application mal pans├йe aboutit ├а une usine ├а gaze (GHG)
T G Manikandan
Honored Contributor

Re: float to string conversion problem

It is working for me using gcc.
Might be your compiler is not supporting this option of string to float conversion.


Thanks
LEJARRE Patrick
Advisor

Re: float to string conversion problem

hi Benoit,

HP-UX 11.00 - C/ANSIC - cc with no option, but you can easily add some.

Bye
benoit Bruckert
Honored Contributor

Re: float to string conversion problem

I don't have the Ansi C compiler on my site !! Then I can't test with this compiler...
I made the test on a linux, it's OK also. That's very strange.
You can try with gcc (install it on your HP-UX, it's available on many portal center), don't forget binutils.

You can also try with a double instead of a float...

Une application mal pans├йe aboutit ├а une usine ├а gaze (GHG)
A. Clay Stephenson
Acclaimed Contributor

Re: float to string conversion problem

I could only reproduce your problem (more or less) with ANSI/C with these options:
cc -Ac +r myfile.c

The result I got was 0.00000000000. It appears that you must be using the +r which inhibits the automatic promotion of float to double when passing arguments (in this case to sprintf). In this context, it makes sense what is happening.

Note: +r may be being set in CCOPTS.

To test if this is the problem, make this change:
sprintf(s,"%10.10f",(double) num);

If it ain't broke, I can fix that.