[comp.unix.aix] ? write and read double as text reliably

apperson@brahms.udel.edu (Apperson H Johnson) (01/18/91)

What is the best way to write double precision numbers if
1. they are to be read by people
2. they are to bre read by a C program, and MUST preserve their exact values.

I need a general format that will preserve all the significant bits of any 
double I write.

I have tried "%.30g" with the following results

2 of 4 systems tried do NOT preserve the values of the floats
across sprintf/sscanf (I tried Xenix 386, SCO Unix, AIX 3.1, Sun OS)

NOTE that NO TWO systems printed EXACTLY the SAME values !!! 

Is there a portable, general solution to this problem? 

It would be nice if system A could read what it wrote (exactly)
it would be REAL nice if for any two systems (A,B) A could read
what B wrote (exactly) - don't any standards cover this ? 

---------------------  tear on dotted line ------------------------------------
#include <stdio.h>

char *s1 = "0.12345678901234547890123456789012345678901234567890";
/* note that i dont REALLY expect all of these digits to affect the value,
   i just want to guarantee excess significant digits */


char s2[128];

main()
{
	double d1, d2, atof();
	
	d1 = atof(s1);
	sprintf(s2,"%.60g",d1);
	sscanf(s2,"%lf",&d2);
	
	printf("d1 and d2 are %sequal!\n", d1 == d2 ? "" : "NOT ");
	printf("s1 = %s\nd1 = %.60g\ns2 = %s\nd2 = %.60g\n",
	   s1,d1,s2,d2);
		
}

----------------------- cry on dotted line ------------------------------------

thanks for any help you can offer,
apperson@brahms.udel.edu

sdl@adagio.austin.ibm.com (Stephen Linam) (01/23/91)

In article <17815@brahms.udel.edu>, apperson@brahms.udel.edu (Apperson H
Johnson) writes:
|> What is the best way to write double precision numbers if
|> 1. they are to be read by people
|> 2. they are to bre read by a C program, and MUST preserve their exact
values.

I don't have a general answer to your question, but I did find a
bug in AIX 3.1 sprintf() which is causing the specific test case
to fail -- the number emited by the sprintf should be 0.12345678901234548.

I'll open a defect report to fix it in the next release.  Please call in
an APAR to get the fix before then.

--------------------------------------------------------------------
Stephen Linam   AWD Austin   T/L: 793-3674  Bell-net: (512) 832-3674
IBM Internet: sdl@adagio.austin.ibm.com        VNET: LINAM at AUSTIN
Outside:  sdl@glasnost.austin.ibm.com