Operating System - HP-UX
1837976 Members
2802 Online
110124 Solutions
New Discussion

Re: Issue in converting character string to float, double.

 
SOLVED
Go to solution
Saurav_Narain
New Member

Issue in converting character string to float, double.

Hi,
The below mentioned code is running on a HP-UX machine and is giving output as shown below. I could not figure out the reason for getting [641.330017] instead of [641.330000].

Can some body please point out the reason for this?

Thanks,
Saurav

Code:

#include
#include

int main(void)
{
char *cpStr = "00000641.33";

float f = 0.0;
double d = 0.0;
double e = 0.0;
float g = 0.0;

f = (float)atof(cpStr);
d = (double)atof(cpStr);
e = atof(cpStr);
g = atof(cpStr);

printf("\n cpStr = [%s] f = [%f] d = [%f] [e] = [%f] [g] = [%f] ... \n\n",cpStr,f,d,e,g);

e = 641.33;
f = (float)e;

printf("\n [e] = [%f] f = [%f] ... \n\n",e,f);

exit(0);
}

Output :

cpStr = [00000641.33] f = [641.330017] d = [641.330000] [e] = [641.330000] [g] = [641.330017] ...


[e] = [641.330000] f = [641.330017] ...
3 REPLIES 3
Hein van den Heuvel
Honored Contributor
Solution

Re: Issue in converting character string to float, double.


Single float is stored in just 32 bits. Ther is only so much precision you get with that.
Roughly that precision is 9 places, but not all number can be stored exactly. Thus the 'odd rounding'.

Read teh following carefully:
http://docs.hp.com/en/B3906-90006/ch02s02.html


Hein.

Dennis Handly
Acclaimed Contributor

Re: Issue in converting character string to float, double.

>Hein: Thus the 'odd rounding'.

Right.
If you asked printf to round to only 2 digits, it would print it "better":
printf("f = [%.2f]\n",f);
f = [641.33]

If you want to see what's in a float vs a double, you could use the %a format on IPF to print it in hex.
printf("f = [%.2f] f = [%a] d = [%a] \n",f,f,d);
f = [641.33] f = [0x1.40aa3e0000000p+9] d = [0x1.40aa3d70a3d71p+9]
Saurav_Narain
New Member

Re: Issue in converting character string to float, double.

Thanks you.